LeetCode 第18题 删除链表的倒数第N个节点


/*
19. 删除链表的倒数第N个节点


给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。

示例:

给定一个链表: 1->2->3->4->5, 和 n = 2.

当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:

给定的 n 保证是有效的。
*/


/*
Definition for singly-linked list.
public class ListNode{
int val; ListNode next;
ListNode(int x) { val = x; }
}
*/

/*
思路:双指针法. 参考官方题解 : https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/solution/
*/

 1 class ListNode17 {
 2 
 3   int val;
 4   ListNode17 next;
 5 
 6   ListNode17(int x) {
 7     val = x;
 8   }
 9 }
10 
11 
12 class Solution19 {
13 
14   public ListNode removeNthFromEnd(ListNode head, int n) {
15     if (head == null || n < 1) {
16       return null;
17     }
18     ListNode dummy = new ListNode(0);
19     ListNode high = dummy;
20     ListNode low = dummy;
21     dummy.next = head;
22     for (int i = 0; i < n && high != null; i++) {
23       high = high.next;
24     }
25     if (high == null) {
26       return null;
27     }
28     while (high.next != null) {
29       low = low.next;
30       high = high.next;
31     }
32     low.next = low.next.next;
33     return dummy.next;
34   }
35 }

 

posted @ 2019-01-20 18:37  散装英语king  阅读(98)  评论(0编辑  收藏  举报