leetcode--19. Remove Nth Node From End of List
来源:互联网 发布:手机模拟笛子软件 编辑:程序博客网 时间:2024/06/18 03:59
Given a linked list, remove the nth node from the end of list and return its head.
For example,
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.
2 pointer的方法。先让一个ptr走n步,使得两个pointer构造出一个gap之后,再共同前进。
构造一个伪头结点,方便处理删除头结点的case。
/** * 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 *pseudo = new ListNode(0); pseudo->next = head; ListNode *p1 = pseudo; ListNode *p2 = pseudo; while(n) { p1 = p1->next; n--; } while(p1->next){ p1 = p1->next; p2 = p2->next; } ListNode *tmp = p2->next; p2->next = p2->next->next; delete tmp; head = pseudo->next; delete pseudo; return head; }};
阅读全文
0 0
- 19. Remove Nth Node From End of List leetcode list
- [LeetCode]19.Remove Nth Node From End of List
- LeetCode 19. Remove Nth Node From End of List
- 19. Remove Nth Node From End of List Leetcode Python
- 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] 19.Remove Nth Node From End of List
- <LeetCode OJ> 19. Remove Nth Node From End of List
- 19. Remove Nth Node From End of List LeetCode
- leetcode 19. Remove Nth Node From End of List
- [LeetCode OJ] 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(JAVA)
- 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 19.Remove Nth Node From End of List
- virtualenv,常用命令和管理(已更新)
- 《统计学习方法》学习笔记(一)——统计学习方法概论
- pat1069(误解的代价)
- rpm与yum 基础 常见命令
- 文档总结6-linux文档权限
- leetcode--19. Remove Nth Node From End of List
- [HDU] 3966 树状数组+启发式树链剖分
- java.lang.Exception: No runnable methods
- CodeForces
- C++继承和派生
- Linux内核参数解析
- Rust : 递归、效率与替代、溢出
- ubuntu 开启SSH服务
- 随机生成汉字图片