方法一:
先遍历一遍链表,得到链表长度,进而得到倒数第n个节点是正数第几个节点。
再遍历链表,进行节点删除操作。
dummyNode技巧应用场景:当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 dummyNode = new ListNode(0,head);
int length = 0;
ListNode cur = head;
while(cur!=null){
cur = cur.next;
length++;
}
ListNode del = dummyNode;
for(int i=0;i<length-n;i++){
del = del.next;
}
del.next = del.next.next;
return dummyNode.next;
}
}
方法二:
左右指针节点,右节点先遍历到第n个节点。
左节点和右节点一起向后遍历,当右节点遍历到最后一个节点时,左节点就是倒数第n-1个节点。
/**
* 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 dummyNode = new ListNode(0,head);
ListNode right = dummyNode;
ListNode left = dummyNode;
for(int i=0;i<n;i++){
right = right.next;
}
while(right.next!=null){
left = left.next;
right = right.next;
}
left.next = left.next.next;
return dummyNode.next;
}
}