(Leetcode)Double pointer to implement delete Linklist node
2015-09-11 04:21
507 查看
Problem:
Given a linked list, remove the nth node from the end of list and return its head.
It’s great to use double pointer to delete node, the double pointer always store the next node’s address.
runtime snapshot better to understand
Given a linked list, remove the nth node from the end of list and return its head.
It’s great to use double pointer to delete node, the double pointer always store the next node’s address.
ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode** t1 = &head, *t2 = head;// cout<<(&t2)<<" "<<t2<<" "<<&head<<" "<<head<<endl;//t2'value is same as head's value,because //thet all point to real head!. cout<<t1<<endl;//t1's value is head pointer's address; for(int i = 1; i < n; ++i) { t2 = t2->next; cout<<" t2: "<<t2<<endl; } while(t2->next != NULL) { t1 = &((*t1)->next);//t1 store the next node's address cout<<"t1:"<<t1<<endl; cout<<"*t1:"<<*t1<<endl; t2 = t2->next; } *t1 = (*t1)->next;//*t1 is next node ; return head; } }; int main(int argc, char const *argv[]) { Solution A; int a[5]={1,2,3,4,5}; ListNode *head=new ListNode(a[0]); ListNode *p=head; int i=1; while(i<5) { ListNode * q=new ListNode(a[i]); p->next=q; p=q; i++; } p=head; while(p!=NULL) { cout<<(*p).val<<endl; p=p->next; } cout<<"-----"<<endl; head=A.removeNthFromEnd(head,3); while(head!=NULL) { cout<<head->val<<endl; head=head->next; } return 0; }
runtime snapshot better to understand
相关文章推荐
- Leetcode Remove Nth Node From End of List
- nodejs中间件详解
- Node.js 学习资源
- lightoj 1094 Farthest Nodes in a Tree 【树的直径 裸题】
- 如何用 OneAPM 优化你的 Node.js 应用?
- 如何用 OneAPM 优化你的 Node.js 应用?
- nodejs图片裁剪、缩放、水印
- node.js安装及grunt插件,如何进行脚本压缩
- Intellij IDEA+nodejs router没有post方法
- 创建一个简单的express工程
- Count Complete Tree Nodes -- leetcode
- Reverse Nodes in k-Group
- Swap Nodes in Pairs
- Remove Nth Node From End of List
- nodejs--express4.x session用法
- Leetcode52: Delete Node in a Linked List
- 【leetcode】Count Complete Tree Nodes -C++
- [环境]搭建Node+NPM+Grunt+Ruby开发环境
- LeetCode Populating Next Right Pointers in Each Node II
- LeetCode Populating Next Right Pointers in Each Node II