19. Remove Nth Node From End of List
来源:互联网 发布:js调用android的方法 编辑:程序博客网 时间:2024/06/10 10:46
题目:
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.
题意:
给定一个链表,删除从链表末尾数第n个节点。
note:
1、给定的n值一直是有效的;
2、试着使用one-pass算法实现;
思路:
设定两个都在相同位置的指针,使一个指针先走n步,之后两个指针一起往后走,当先走的那个元素到达链表末尾时,删除后走的那个元素的下一个元素即可。
代码:4ms
/** * 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 dummy(-1); dummy.next = head; ListNode *pre = &dummy, *cur = &dummy; //定义两个指针 while(n){ //其中一个指针先走n步 pre = pre->next; n--; } while(pre->next){ //当先走的指针没有走到链表末尾时,两个指针一起向后走 pre = pre->next; cur = cur->next; } ListNode *tmp = cur->next; //删掉第n个元素 cur->next = tmp->next; delete tmp; return dummy.next; }};
0 0
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node from End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- java环境变量配置
- MVC 通过BundleConfig 将JS和CSS文件引入到视图中
- 广义线性模型分类
- 开户自动旋转在某应用中横屏后关闭自动旋转,该应用不会自动恢复到竖屏,
- matlab中的sort函数
- 19. Remove Nth Node From End of List
- Spark算子篇-combineByKey实战
- FragmentTabHost的使用--仿微信首页搭建
- 关于一道简单的Java 基础面试题的剖析: short s1=1;s1 = s1 +1会报错吗?
- Python中@property的粗略理解
- 阿里面试题总结
- 【天梯赛-练习题】L2-007 家庭房产
- Objective C类方法load和initialize的区别
- 使用jutil测试程序出现错误java.lang.Exception: No tests found matching [{ExactMatcher:fDisplayName=classestest]