leetcode19. Remove Nth Node From End of List删除链表的倒数第N个节点

题目:

Given a linked list, remove the n-th node from the end of list and return its head.

Example:

Given linked list: 1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:

Given n will always be valid.

给定一个链表,删除链表的倒数第 个节点,并且返回链表的头结点。

示例:

给定一个链表: 1->2->3->4->5, 和 n = 2.

当删除了倒数第二个节点后,链表变为 1->2->3->5.

说明:

给定的 n 保证是有效的。

思路:两个指针,cur先移动n步,pre指向第一个节点。然后两个一起移动,直到cur移动到最后一个元素,pre所指向的就是倒数第n个节点。注意的是链表长度为n删除倒数第n个几点, 那就直接返回head->next;

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        if(head==NULL) return NULL;
        ListNode *cur=head,*pre=head;
        for(int i=0;i<n;++i) cur=cur->next;
        if(cur==NULL) return head->next;
        while(cur->next)
        {
            cur=cur->next;
            pre=pre->next;
        }
        pre->next=pre->next->next;
        return head;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_21997625/article/details/85113519
今日推荐