146-Delete the last N nodes of the linked list

The problem is as follows:
Given a linked list, delete the nth node from the bottom of the linked list, and return the head node of the linked list.
Given a linked list: 1->2->3->4->5, and n = 2.

When the penultimate node is deleted, the linked list becomes 1->2->3->5.

Problem-solving ideas:
1. Calculate the length of the linked list, delete the last nth node, which means delete the last len%n node
2. Both the fast and slow pointers point to the head node, the slow pointer does not move at the head node, and the fast pointer goes backward Go to n nodes
3. If the fast pointer points to empty at this time, it means that the first node to be deleted is return head->next, that is, the delete operation is completed
4. If the fast pointer is not empty at this time, then speed The pointers start to move backwards together until the fast pointer reaches the last node position. At this time, the slow pointer points to the predecessor node of the node to be deleted.

ListNode *removeNthFromEnd(ListNode *head, int n)
{
    
    
    if (head == NULL || n <= 0)
        return head;

    ListNode *p = head;
	ListNode *q = head;
    int len = 0;//定义len记录链表的长度
    while (p != NULL)//计算链表的长度 
    {
    
    
        len++;
        p = p->next;
    }
    n = n % len;//求出最简n 
    p = head;//p回到头结点 
    while (p != NULL && n--)//p往后走n个结点
    {
    
    
        p = p->next;
    }
    if (p == NULL)//说明要删除的那个结点是第一个结点 
        return head->next;
    while (p->next != NULL)//p,q一起往后走
    {
    
    
        p = p->next;
        q = q->next;
    }
    q->next = q->next->next;//删除结点 
    return head;//返回头结点即返回新链表 
}

The code running diagram is as follows:
Insert picture description here

Guess you like

Origin blog.csdn.net/LINZEYU666/article/details/112980425