一、问题描述
Given a linked list, remove the nth node from the end of list and return its head.
For Example:
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
二、解题思路
思路一:遍历两遍链表,第一遍计算链表的总长度,第二遍定位需要移除的链表元素。
思路二:遍历一遍链表,定义两个变量first和second,分别指向链表不同的元素,并且满足first-second=n,然后first和second不断自增,当first指向的元素的下一个是null是,second就指向了目标元素的上一个,然后执行移除操作。
三、代码
思路一:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode result=new ListNode(0);//如果result直接指向head,需要考虑当链表的长度等于n时,即移除第一个链表元素时这种情况。
result.next=head;
if(head==null || n<=0)
return head;
int count=0;
while(head!=null){
head=head.next;
count++;
}
int i=0;
head=result;
while(true){
if(i==count-n){
head.next=head.next.next;
break;
}
head=head.next;
i++;
}
return result.next;
}
}
思路二:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode result=new ListNode(0);
result.next=head;
if(head==null || n<=0)
return head;
ListNode first=result;
ListNode second=result;
for(int i=0;i<n;i++){
first=first.next;
}
while(first.next!=null){//如果这里判断的是first!=null,则前面first需要移动n+1
first=first.next;
second=second.next;
}
second.next=second.next.next;
return result.next;
}
}