双指针的应用
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.
题意:很简单就是删除链表的倒数第n个结点(n已经确保有效),并且要通过一次遍历就得到删除后的链表
思路:采用快慢指针,控制两个结点的距离 = n,慢指针后面的第一个元素就是要删除的元素。
细节:当遇到【1,2】 删除倒数第2个结点,这种情况下需要特数处理链表,只要出现快慢指针距离 = 链表长度的时候,必定是删除头结点
Java代码实现
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode qucik = head;
ListNode slow = head;
while(n-- != 0)
qucik = qucik.next;
//已经保证有效,判断是否删除头结点
if(qucik == null)
return head.next;
while(qucik.next != null) {
qucik = qucik.next;
slow = slow.next;
}
slow.next = slow.next.next;
return head;
}
}