leetcode 19. Remove Nth Node From End of List 单向链表删除第n个数
2016-11-10 21:23
471 查看
代码:
/**
* 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 *now = head;
ListNode *tmp = head;
int len=0;
while(tmp) {
len++;
tmp=tmp->next;
}
n=len-n;
if(head->next==NULL) return now=NULL;
if(n==0){
return head->next;
}
int num=0;
while(head){
if(num+1==n) {
if(head->next){
ListNode *tmp = head->next;
head->next=tmp->next;
head=head->next;
tmp=NULL;
} else {
head->next=NULL;
head=head->next;
break;
}
}
else head=head->next;
num++;
}
//cout<<now->val<<endl;
return now;
}
};
/**
* 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 *now = head;
ListNode *tmp = head;
int len=0;
while(tmp) {
len++;
tmp=tmp->next;
}
n=len-n;
if(head->next==NULL) return now=NULL;
if(n==0){
return head->next;
}
int num=0;
while(head){
if(num+1==n) {
if(head->next){
ListNode *tmp = head->next;
head->next=tmp->next;
head=head->next;
tmp=NULL;
} else {
head->next=NULL;
head=head->next;
break;
}
}
else head=head->next;
num++;
}
//cout<<now->val<<endl;
return now;
}
};
相关文章推荐
- Leetcode:19 Remove Nth Node From End of List(在链表中删除倒数第n个数)
- LeetCodet题解--19. Remove Nth Node From End of List(删除链表的倒数第n个元素)
- 【LeetCode题解】19_删除链表的倒数第N个节点(Remove-Nth-Node-From-End-of-List)
- leetcode_[python/C++]_19. Remove Nth Node From End of List(删除链表末第n个节点)
- Leetcode刷题记——19. Remove Nth Node From End of List(删除链表倒数第N项)
- [LeetCode] 19. Remove Nth Node From End of List 删除链表的倒数第N个节点 @python
- LeetCode 19. Remove Nth Node From End of List(删除链表)
- leetcode-19. Remove Nth Node From End of List(删除链表倒数第N个节点)
- [C++]LeetCode 19: Remove Nth Node From End of List(删除链表中倒数第n个节点)
- LeetCode 19. Remove Nth Node From End of List--删除链表的倒数第n个结点
- [LeetCode-19] Remove Nth Node From End of List(删除链表中倒数第N个节点)
- leetcode:Remove Nth Node From End of List(删除链表倒数第n个节点)【面试算法题】
- LeetCode 19 Remove Nth Node From End of List(从列表尾部删除第N个结点)(*)
- leetCode 19. Remove Nth Node From End of List 链表
- leetcode 19. Remove Nth Node From End of List(链表)
- leetcode_19题——Remove Nth Node From End of List(链表)
- [LeetCode]—Remove Nth Node From End of List 删除链表的倒数第n个节点
- Leetcode Remove Nth Node From End of List 删除链表倒数第n个元素
- [Leetcode] remove nth node from the end of list 删除链表倒数第n各节点
- leetCode 19.Remove Nth Node From End of List(删除倒数第n个节点) 解题思路和方法