【Leetcode】Remove Nth Node From End of List
来源:互联网 发布:大数据画像系统 编辑:程序博客网 时间:2024/04/30 13:52
题目:
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.
代码1:
/** * 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 *FirstPtr,*SecondPtr; FirstPtr=SecondPtr=head; int count=0; while(FirstPtr!=NULL){ FirstPtr=FirstPtr->next; count++; } if(count==n)return head->next; while(count-n>1){ SecondPtr=SecondPtr->next; count--; } ListNode *to_delete=SecondPtr->next; SecondPtr->next=SecondPtr->next->next; delete to_delete; return head; }};
解题思路2:建立一个位于头节点之前的节点(该节点的next域指向头节点),设立两个指向该节点的指针,让第一个指针先往后走n步,然后两个指针一起向后走直到最后一个节点,此时第二个指针所在位置的下一个节点就是需要删除的节点。
/** * 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 Forehead(0); Forehead.next=head; ListNode *FirstPtr,*SecondPtr; FirstPtr=SecondPtr=&Forehead; while(n--){ FirstPtr=FirstPtr->next; }; while(FirstPtr->next){ FirstPtr=FirstPtr->next; SecondPtr=SecondPtr->next; } ListNode *to_delete=SecondPtr->next; SecondPtr->next=SecondPtr->next->next; delete to_delete; return Forehead.next; }};
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
- 中断子系统(2)APIC
- 计算机远程服务相关设置
- 调试备忘QT编程No such slot的解决方法
- 设置别名 linux
- 【黑马程序员】集合
- 【Leetcode】Remove Nth Node From End of List
- 增广贤文
- eclipse 安装freemarker 模板增加编码颜色
- seaJS实例模板
- jsp九大内置对象总结
- 笔记本电脑
- C语言中的小启发(陆续更新。。。)
- 正文 第二章 通背拳
- 为什么不使用SOA方式,要提出这个新的东东OData