Remove Nth Node From End of List (java实现)
[题目描述]
(https://leetcode.com/problems/remove-nth-node-from-end-of-list/)
第一种解题思路:
初始化头结点,然后从前到后统计链表长度,当first指针为空时,将长度赋值为长度-n,再从前到后遍历一次,遍历到空时,说明这个节点为要移除的节点,然后将first.next指向first.next.next即可将剩余部分相连接,返回结果。
/**
* 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 dummy = new ListNode(0);
dummy.next = head;
int length = 0;
ListNode first = head;
while (first != null) {
length++;
first = first.next;
}
length -= n;
first = dummy;
while (length > 0) {
length--;
first = first.next;
}
first.next = first.next.next;
return dummy.next;
}
}
第二种解题思路:
定义两个指针,first指针向前移动n步后,first和second指针同时移动,当first指针移动到末尾时,second指针指向末尾倒数第n个要删除的节点,令second.next = second.next.next,返回头指针,得到结果
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode l = dummy;
ListNode r = dummy;
for(int i = 1;i<=n+1;i++){
l = l.next;
}
while(l!=null){
l = l.next;
r = r.next;
}
r.next = r.next.next;
return dummy.next;
}