我用java刷 leetcode 19. 删除链表的倒数第N个结点
Posted 深林无鹿
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了我用java刷 leetcode 19. 删除链表的倒数第N个结点相关的知识,希望对你有一定的参考价值。
这里有leetcode题集分类整理!!!
题目难度:中等
题目描述:
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
进阶:你能尝试使用一趟扫描实现吗?
myAC:(计算链表长度)
/**
* 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) {
int len = getLength(head);
ListNode dummyHead = new ListNode(0, head), curr = dummyHead;
for (int i = 1 ; i < len - n + 1; i ++) {
curr = curr.next;
}
curr.next = curr.next.next;
return dummyHead.next;
}
public int getLength(ListNode head) {
int res = 0;
while (head != null) {
head = head.next;
res ++ ;
}
return res;
}
}
官解:(栈)
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0, head);
Deque<ListNode> stack = new LinkedList<ListNode>();
ListNode cur = dummy;
while (cur != null) {
stack.push(cur);
cur = cur.next;
}
for (int i = 0; i < n; ++i) {
stack.pop();
}
ListNode prev = stack.peek();
prev.next = prev.next.next;
ListNode ans = dummy.next;
return ans;
}
}
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/solution/shan-chu-lian-biao-de-dao-shu-di-nge-jie-dian-b-61/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
官解:双指针(空间O1)
关键思路: first 比 second 超前 n 个节点
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;
return dummy.next;
}
}
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/solution/shan-chu-lian-biao-de-dao-shu-di-nge-jie-dian-b-61/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
以上是关于我用java刷 leetcode 19. 删除链表的倒数第N个结点的主要内容,如果未能解决你的问题,请参考以下文章
我用java刷 leetcode 剑指 Offer 25. 合并两个排序的链表