您的位置:首页 > Web前端 > Node.js

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

2016-03-06 14:12 549 查看
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].
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: