第六周LeetCode

来源:互联网 发布:浙大网新恒天软件福利 编辑:程序博客网 时间:2024/05/22 15:01

题目
难度 Medium

Remove Nth Node From End of List
Given a linked list, remove the nth node from the end of list and return its head.

For 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.
Try to do this in one pass.

实现思路

这个题目好像一起上课讨论过,所以大概记得one pass怎么做。大概就是用三个指针(两个也可以),分别是prev,cur,nNext,prev为cur当前节点的前一个节点,而nNext就是当前节点往后数的第n个节点,比如有链表1->2->3->4->5, n = 2,cur为2这个节点,则prev为1节点,nNext为4节点。当nNext为链表最后一个节点的下一个(即为NULL)时,cur就是要找的从end开始第n个节点。即遍历链表时一直把nNext当成end,则cur为要删除的那个,当链表遍历结束即nNext为空,就找到cur了。
如果cur为头指针,删除时要特殊处理。

实现代码

/** * 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) {        ListNode* prev = NULL;        ListNode* cur = head;        ListNode* nNext = head;        int count = 0;        while (nNext != NULL) {            count++;            if (count > n) {                prev = cur;                cur = cur->next;            }            nNext = nNext->next;        }        if (prev == NULL) {            cur = head;            head = head->next;            delete cur;        } else {            prev->next = cur->next;            delete cur;        }        return head;    }};
原创粉丝点击