Question:
Given a linked list, remove the nth node from the end of list and return its head.
给定一个链表,从列表末端删除n个节点并返回它的头部。
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.
Note:
Given n will always be valid.
Try to do this in one pass.
给定的n一直有效,尝试着一次通过。
Answer:
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
//没有待删除的结点
if (n==0)
return head;
ListNode countHead = head;
int listNum = getListNum(countHead);
//删除所有结点
if (listNum==1)
return null;
else{
if(n==listNum){
head=head.next;
return head;
}
int count = 1;
ListNode startHead = head;
ListNode preHead = null;
while(count<listNum-n+1){
if(count==listNum-n){
preHead = startHead;//待删除结点的前一个结点
}
startHead=startHead.next;
count++;
}
//System.out.println(count);
preHead.next=startHead.next;
return head;
}
}
public int getListNum(ListNode head){
int nodeNum = 0;
while(head.next!=null){
nodeNum++;
head=head.next;
}
nodeNum++;
return nodeNum;
}
}
class ListNode{
int val;
ListNode next;
ListNode(int x){val=x;}
}