leetcode-19. Remove Nth Node From End of List(删除链表倒数第N个节点)
2017-05-23 19:53
771 查看
https://leetcode.com/problems/remove-nth-node-from-end-of-list/#/description
假设有一个结构体代表每个链表中的节点
struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
问题描述:
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个值,记得王道的书里有一道类似的题。
设置两个指针,一个不动,另一个移动n个位置,然后两个指针一起移动。当第二个指针移动到最后,则第一个指针,正好移动到倒数第n个位置。
代码如下:
假设有一个结构体代表每个链表中的节点
struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
问题描述:
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个值,记得王道的书里有一道类似的题。
设置两个指针,一个不动,另一个移动n个位置,然后两个指针一起移动。当第二个指针移动到最后,则第一个指针,正好移动到倒数第n个位置。
代码如下:
/** * Definition for singly-linked list. * public class ListNode { * int val;//节点的值 * ListNode next;//下一个指针 * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { ListNode start=new ListNode(0);//创建一个节点,含参构造方法。 ListNode s=start,e=start; s.next=head; for(int i=0;i<=n;i++) { e=e.next; } while(e!=null) { s=s.next; e=e.next; } s.next=s.next.next; return start.next; } }
相关文章推荐
- 【LeetCode题解】19_删除链表的倒数第N个节点(Remove-Nth-Node-From-End-of-List)
- [LeetCode-19] Remove Nth Node From End of List(删除链表中倒数第N个节点)
- [LeetCode] 19. Remove Nth Node From End of List 删除链表的倒数第N个节点 @python
- [C++]LeetCode 19: Remove Nth Node From End of List(删除链表中倒数第n个节点)
- [LeetCode] 19. Remove Nth Node From End of List 移除链表倒数第N个节点
- LeetCode 19. Remove Nth Node From End of List--删除链表的倒数第n个结点
- [LeetCode]—Remove Nth Node From End of List 删除链表的倒数第n个节点
- leetcode_[python/C++]_19. Remove Nth Node From End of List(删除链表末第n个节点)
- LeetCodet题解--19. Remove Nth Node From End of List(删除链表的倒数第n个元素)
- LeetCode(Remove Nth Node From End of List)删除链表倒数第n个节点
- leetcode:Remove Nth Node From End of List(删除链表倒数第n个节点)【面试算法题】
- 【LeetCode】Remove Nth Node From End of List 删除链表中倒数第n个节点- Easy +
- 【Leetcode】19. Remove Nth Node From End of List - 删掉链表倒数第n个节点
- leetCode 19.Remove Nth Node From End of List(删除倒数第n个节点) 解题思路和方法
- Remove Nth Node From End of List 链表删除倒数第N个元素@LeetCode
- Leetcode:19 Remove Nth Node From End of List(在链表中删除倒数第n个数)
- LintCode Remove Nth Node From End of List 删除链表中倒数第n个节点
- LeetCode 19. Remove Nth Node From End of List(删除单链表倒数第N个结点)
- LeetCode 19 Remove Nth Node From End of List 移除倒数第N个节点
- [LeetCode] Remove Nth Node From End of List 移除链表倒数第N个节点