leetcode刷题,总结,记录,备忘 19
来源:互联网 发布:js 移除class中的一个 编辑:程序博客网 时间:2024/06/07 11:36
leetcode19Remove Nth Node From End of List
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.
Note:
Given n will always be valid.
Try to do this in one pass.
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode * function(ListNode * head, int * n) { ListNode * result; if (head->next) { result = function(head->next, n); } else { result = NULL; } if (--*n == 0) { return result; } else { head->next = result; return head; } } ListNode* removeNthFromEnd(ListNode* head, int n) { int m = n; if (head == NULL) { return NULL; } ListNode * result = function(head, &m); return result; }};讨论区看到一个非常厉害的解决方法,用2个指针,先用一个指针走n-1个位置,然后第二个指针与第一个指针一起走,直到第一个指针为null,此时第二个指针就是要删除的节点,并且第二个指针使用的是二级指针的方式,可以直接通过二级指针的地址修改该节点上的值,非常巧妙。
class Solution{public: ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode** t1 = &head, *t2 = head; for(int i = 1; i < n; ++i) { t2 = t2->next; } while(t2->next != NULL) { t1 = &((*t1)->next); t2 = t2->next; } *t1 = (*t1)->next; return head; }};
0 0
- leetcode刷题,总结,记录,备忘 19
- leetcode刷题。总结,记录,备忘 104
- leetcode刷题。总结,记录,备忘 100
- leetcode刷题。总结,记录,备忘 191
- leetcode刷题。总结,记录,备忘。168
- leetcode刷题, 总结,记录,备忘 171
- leetcode刷题 ,总结,记录,备忘。144
- leetcode刷题,总结,记录, 备忘 141
- leetcode刷题,总结,记录,备忘。116
- leetcode刷题,总结,记录,备忘。96
- leetcode刷题。记录,总结,备忘。217
- leetcode 刷题, 总结,记录,备忘 35
- leetcode刷题,总结,记录,备忘 226
- leetcode刷题,总结,记录,备忘 169
- leetcode刷题,总结,记录,备忘137
- leetcode刷题,总结,记录,备忘83
- leetcode刷题,总结,记录,备忘70
- leetcode刷题,总结,记录,备忘 108
- hdu 5800 计数dp
- web框架——struts2操作
- Django 导出 Excel 代码详解
- 贝叶斯推断及其互联网应用(二):过滤垃圾邮件
- Actor::updateMassFromShapes: Compute mesh inertia tensor failed for one of the actor's mesh shapes!
- leetcode刷题,总结,记录,备忘 19
- 日常小结-关于模拟登陆的小结-fastjson库的使用小结
- 朴素贝叶斯分类器的应用
- Codeforces GYM 100738C Rating Shuffle
- HoloLens SDK开发(Unity3d+VS2015+HoloLens Emulator),项目配置
- Java并发编程:线程池的使用
- 快速排序(QuickSort)原理及Java 实现
- 优秀软件诞生的12个必备技术构成
- hibernate反向工程