标签:follow get his you could pointer 头结点 ext pass
删除链表中倒数第n个结点
题目:LeetCode19
Given a linked list, remove the n-th node from the end of list and return its head.
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.
Follow up:
Could you do this in one pass?
思路:
题目要求one pass,即只遍历一遍链表并完成删除操作。
如果删除倒数第n个结点,需要定位到该结点的前一个结点。
两种情况,1)删除的结点是头结点;2)删除的结点非头结点
首先:定义一个快指针,从链表头部走n步。如果此时已经指向null,说明要删除的结点是该链表的头结点,则返回head.next。即case 1。
case 2: 如果快指针此时没有指向null, 定义一个慢指针指向头结点,快慢指针同时向后移动,当快指针指向最后一个结点时,慢指针指向被删除结点的前一个。
操作慢指针,删除倒数第n个结点(slow.next = slow.next.next)。(注意:这里慢指针和快指针至少相差1,所以当快指针指向最后一个结点,slow.next.next 不会nullpointer异常。)
代码:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { ListNode fast = head; while (n > 0) { fast = fast.next; n--; } if (fast == null) { return head.next; } ListNode slow = head; while (fast.next != null) { slow = slow.next; fast = fast.next; } slow.next = slow.next.next; return head; } }
LeetCode19- Remove Nth Node From End of List-Medium
标签:follow get his you could pointer 头结点 ext pass
原文地址:https://www.cnblogs.com/Jessiezyr/p/12985255.html