您的位置:首页 > Web前端 > Node.js

[LeetCode] 19. Remove Nth Node From End of List ☆

2017-02-18 17:02 471 查看
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个节点,并且说明了n一定是有效的,限定一次遍历解决问题。首先定义两个指针 first 和 last,first 指向第一个节点,last 指向第 n+1 个节点;两个节点同时向后撸,直到 last.next 为 null 的时候,说明当前 first.next 即为待删除节点,直接 first.next.next = first.next 即可删除,然后返回 head。注意,如果一开始的时候 last 就为 null,说明 head 节点就是带删除的节点,直接返回 head.next 即可。

/**
* 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 first = head;
ListNode last = head;
while (n-- > 0) {
last = last.next;
}

if (last == null) {
return head.next;
}

while (last.next != null) {
first = first.next;
last = last.next;
}

first.next = first.next.next;
return head;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: