leetcode: Remove Nth Node From End of List
来源:互联网 发布:windows隐藏任务栏图标 编辑:程序博客网 时间:2024/04/30 20:16
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.
两个指针,快的先走n步,然后一起走,快的走到NULL,删除慢的指向的节点
/** * 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; int cnt = 0; ListNode *p = head; while(p){ ++cnt; p = p->next; } if( cnt < n) return head; p = head; while( n){ p = p->next; --n; } ListNode *q = head, *pre = NULL; while(p){ p = p->next; pre = q; q = q->next; } if( pre == NULL) return head->next; pre->next = q->next; delete q; return head; }};
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
- Google Java Style
- Android Studio代码自动检测错误提示
- python简史
- 二叉搜索树
- 稍微复杂的sql逻辑(从数据库逆序查找有限条记录(limit))并按相反顺序输出
- leetcode: Remove Nth Node From End of List
- SRM 554 - 500 TheBrickTowerMediumDivOne
- CAS实现单点登录的时序图
- undefined与null的区别
- SSH原理与运用
- Java——动态加载任意目录下的架包
- UIApplicationLaunchOptionsRemoteNotificationKey
- Run Loop
- android 控件翻转切换布局