C++ implementation of a single linked list to delete the penultimate k node method

  • 2020-05-19 05:14:24
  • OfStack

The example of this article describes the method of C++ to delete the penultimate k node in a single linked list. I will share it with you for your reference as follows:

Topic:

Delete the penultimate k node in a single linked list

Problem solving ideas and algorithm code:

The ruler method defines two Pointers to the header node of the chain. First, let one of them walk k step, and then the two Pointers start to walk at the same time. When the pointer that goes first reaches the end, the node pointed by the pointer that goes last is the node that needs to be deleted.

Single linked list structure definition:


typedef struct Node
{
  int data;
  struct Node* next;
}node, *pLinkedList;

Delete the operation code of the penultimate K node:


//head Represents the header node 
Node* removeLastKthNode(pLinkedList head, int k)
{
  if (NULL == head->next || k < 1)
    return head;
  pLinkedList cur = head; //1 Pointer to the no. 
  pLinkedList ret = head; //2 Pointer to the node to be deleted 
  pLinkedList pre = NULL; //pdel Before the node to be deleted 1 A node 
  /*
  head  1  2  3  4  5
  cur
  ret
  */
  while (k > 0 && cur != NULL)
  {
    k--;
    cur = cur->next;
  }
  // When you get to the end of the list, k Still greater than the 0 , known k The value is greater than the length of the list 
  if (k > 0 && cur == NULL)
  {
    cout << "k The value is greater than the length of the list " << endl;
    return head;
  }
  //k == 0 When, 1 The pointer and 2 The number pointer goes at the same time ,ret Is the node to be deleted 
  if (k == 0)
  {
    while (cur != NULL)
    {
      pre = ret;
      cur = cur->next;
      ret = ret->next;
    }
    /*k = 2 when 
    head  1    2   3    4   5  NULL
               pre   ret     cur
     That is to ask for deletion ret node 
    */
    pre->next = ret->next;
    free(ret);
    ret = NULL;
    return head;
  }
}

I hope this article has helped you with C++ programming.


Related articles: