LeetCode OJ刷题历程——Remove Nth Node From End of List

来源:互联网 发布:pl sql developer下载 编辑:程序博客网 时间:2024/06/03 20:55
Given a linked list, remove the nth node from the end of list and return its head.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.

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 *p,*q,*r;int count = 0;r = p = q = head;while(p->next){p = p->next;if(count>=n-1)q = q->next;if(count>=n)r = r->next;count++;}if(count == 0)    head = NULL;else if(r == q)    head = head->next;r->next = q->next;q->next = NULL;return head;    }};
这里只使用了一次遍历,p指针开始遍历,q指针相对于p延迟n-1个时间开始遍历,用以得到倒数第n个结点位置,而r指针用以得到倒数第n+1个结点位置,用以删除操作。

这个题目同样需要注意特殊情况,如链表只有一个结点的情况,应该返回NULL


Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0,1].
0 0
原创粉丝点击