Remove Nth Node From End of List
来源:互联网 发布:ios6卡顿优化 编辑:程序博客网 时间:2024/04/30 13:16
Given a linked list, remove the nth node from the end of list and return its head.
设置双指针p,q,中间间隔n-1,同时移动,q到最后时,p为要删除的节点
/**
* 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) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(head == NULL)
return NULL;
ListNode *p = head,*q = head;
// int t = 0;
if(n == 1){
q = head->next;
if(q == NULL)
return NULL;
while(q->next){
p = p->next;
q = q->next;
}
p->next = NULL;
return head;
}
else if(n != 1){
while(q){
q = q->next;
t++;
if(t == n-1)
break;
}
}
while(q->next){
p = p->next;
q = q->next;
}
p->val = p->next->val;
p->next = p->next->next;
return head;
}
};
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node from End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- 碰到的不认识单词
- 2013.10.30
- 主成分分析
- Java中static、final用法小结
- select accept
- Remove Nth Node From End of List
- junit3与junit4的区别及其兼容问题
- Java中变量内存分配机制
- 关于"*"和"++"优先度问题
- 如何识别高级的验证码
- C语言内存分配策略
- topcoder-srm-594
- Edit组件控制字体居中,居左,居右
- 我的Twitter面试失败了