菜鸟刷leetcode 19. Remove Nth Node From End of List
来源:互联网 发布:中央财经大学知乎 编辑:程序博客网 时间:2024/06/07 06:53
我做的还是最简单粗暴的做法,因为想不出简单算法,也不知道怎么只用一个loop。。
于是用c,
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) { struct ListNode* H; H=head; int len=1; while(H->next!=NULL) { len++; H=H->next; } int pos=len-n,num=1; if(n==len) { head=head->next; return head; } H=head; while(num!=pos) { num++; H=H->next; } H->next=H->next->next; return head; }然后看了discuss,发现巧妙的办法,用两个指针,通过他们之间的差值来确定。
class Solution {public: ListNode* removeNthFromEnd(ListNode* head, int n) { if (!head) return head; ListNode dummy(0), * t = &dummy, *s = &dummy; dummy.next = head; while (t && t->next) { if (n-- <= 0) s = s->next; t = t->next; } s->next = s->next->next; return dummy.next; }};
ps,以后写链表的程序,最好先定义一个头指针,即
ListNode dummy(0),*t=&dummy;
dummy.next=head;然后最后返回值为dummy.next即可。
0 0
- 菜鸟刷leetcode 19. Remove Nth Node From End of List
- 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
- IP地址,子网掩码,默认网关,路由总结
- 微信JSSDK 突然出现invalid signature无效签名
- Tomcat的使用(详细流程)
- [ATF]ARMv8 psci cpu off api
- 生产者与消费者(一)
- 菜鸟刷leetcode 19. Remove Nth Node From End of List
- 如何用java写一个简单的记事本。
- Remote Debugging之放开那个webview让我来调戏(试)
- 商城购物车模块-自定义数字加减控件
- log4j将包内的所有类日志指定文件输出
- jsp九大内置对象
- 应用大数据和机器学习技术实现车险全流程智能化的方案(中) -理赔流程智能化改造
- 最长路问题
- OpenGL(一)绘制圆、五角星、正弦曲线