Leetcode Remove Nth Node From End of List
来源:互联网 发布:网络黑白 花无涯 编辑:程序博客网 时间:2024/06/17 18:41
题意:删除链表中倒数第i个元素。
思路:用堆栈完成计数工作。
/** * 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) { if(head == NULL) return head; stack<ListNode*> mys; ListNode* myhead = new ListNode(0); ListNode* next = head; myhead->next = next; mys.push(myhead); while(next) { mys.push(next); next = next->next; } ListNode* after = NULL; next = mys.top(); mys.pop(); while(n --) { after = next->next; next = mys.top(); mys.pop(); } next->next = after; return myhead->next; }};
另一种只遍历一边的做法是,在链表中标记第i个元素到结尾的长度。这样做目的是记录从头到达i-1个元素需要的循环次数。
/** * 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* myhead = new ListNode(0); myhead->next = head; ListNode* mark = head; ListNode* next = myhead; while(n --) { mark = mark->next; } while(mark) {//cout << "here" <<endl; mark = mark->next; next = next->next; } next->next = next->next->next; return myhead->next; }};
0 0
- LeetCode[Linked List]: Remove Nth Node From End of List
- 19. Remove Nth Node From End of List leetcode list
- [Leetcode]LeetCode 19:Remove Nth Node From End of List
- LeetCode: Remove Nth Node From End of List
- LeetCode: Remove Nth Node From End of List
- [Leetcode] Remove Nth Node From End of List
- LeetCode: Remove Nth Node From End of List
- leetcode 40: Remove Nth Node From End of List
- [LeetCode] Remove Nth Node From End of List
- Leetcode 19 Remove Nth Node From End of List
- [Leetcode] Remove Nth Node From End of List
- [LeetCode]Remove Nth Node From End of List
- LeetCode-Remove Nth Node From End of List
- [LeetCode] Remove Nth Node From End of List
- LeetCode 19: Remove Nth Node From End of List
- LeetCode - Remove Nth Node From End of List
- LeetCode | Remove Nth Node From End of List
- leetcode之Remove Nth Node From End of List
- 如何实现在苹果手机和外界碰撞后再执行某项操作
- ListActivity中点击listview传值到一个新的activity中
- adb端口被占用,百度了很久都解决不了 求助大神!
- xcode8升级问题
- android开发 如何在代码中删除最近打开的任务记录
- Leetcode Remove Nth Node From End of List
- object-c block问题
- 一个显示图片的尝试,任务已实现,但是console总是提示一下内容
- 在vs中发布网站
- android 自定义的view长度大于屏幕宽度
- php与asp与asp.net
- 滚果鼠标到指定位置触发事件。代码不会么写。。。求代码!!
- android studio gradle 编译又报错了,求帮助
- 问一下各位大牛几个Andriod开发的问题