题目链接:
https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
先用粗糙的思路秒了
/**
* 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 temp = head;
ListNode ans = head;
int count = 0;
//如果链表长度是0或者1,返回空
if(head == null || head.next == null) return null;
while(temp != null){
temp = temp.next;
count++;
}
//如果删除的是head节点,直接返回head.next
if(count == n) return head.next;
//是中间节点或者末尾,就用ans来处理
while(count - n - 1 > 0){
count--;
ans = ans.next;
}
ans.next = ans.next.next;
return head;
}
}
思路就是先扫一遍链表记录链表长度,将链表长度为0或者1,或者删除节点为首的特殊情况写出,一般情况再扫一次链表去掉对应节点。
看了一下官方题解,方法二使用栈(正好学习一下Java怎么使用栈的)
/**
* 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 cur = dummy;
Deque<ListNode> stack = new LinkedList<ListNode>();
//把每个节点都存进栈里
while(cur != null){
stack.push(cur);
cur = cur.next;
}
for( int i = 0; i < n; ++i){
stack.pop();
}
ListNode temp = stack.peek();
temp.next = temp.next.next;
dummy = dummy.next;
return dummy;
}
}
方法三:双指针
思路很秀啊,慢指针跟快指针保持n的距离,当快指针到达终点的时候慢指针就是要删除的元素的位置,自己手写了一遍,一次过QAQ
/**
* 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 fast = dummy;
ListNode slow = dummy;
if(head == null || head.next == null) return null;
while(n > 0){
fast = fast.next;
n--;
}
while(fast.next != null){
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
dummy = dummy.next;
return dummy;
}
}