LeetCode No19. 删除链表的倒数第 N 个结点
题目
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
示例 1:
输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
示例 2:
输入:head = [1], n = 1
输出:[]
示例 3:
输入:head = [1,2], n = 1
输出:[1]
提示:
链表中结点的数目为 sz
1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz
进阶:
你能尝试使用一趟扫描实现吗?
思路
基础
先求出链表长度len,然后将倒数第n个数,替换为正数第len-n个数。
进阶
其实就是想到的就是双指针的做法,求倒数第n个节点,也就是说求到链表尾部为n的那个节点,那只要定义两个相差n的指针,大的指针到达链表尾部的时候,小的指针正好在倒数第n个节点上。
AC代码
基础
点击查看代码
/**
* 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 {
private int getLen(ListNode head) {
int len = 0;
while( head.next!=null ) {
head = head.next;
len ++;
}
return len;
}
public ListNode removeNthFromEnd(ListNode head, int n) {
int len = getLen(head);
if( len+1==n ) {
return head.next;
}
int m = len - n;
int cnt = 0;
ListNode node = head;
while( cnt<m ) {
node = node.next;
cnt ++;
}
node.next = node.next.next;
return head;
}
}
点击查看代码
/**
* 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 dummy = new ListNode(0, head);
ListNode first = head;
ListNode second = dummy;
for (int i = 0; i < n; ++i) {
first = first.next;
}
while (first != null) {
first = first.next;
second = second.next;
}
second.next = second.next.next;
ListNode ans = dummy.next;
return ans;
}
}
低调做人,高调做事。