Remove Nth Node From End of List
Given a linked list, remove the n-th node from the end of list and return its head.
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.
Follow up:
Could you do this in one pass?
题目分析
题目不难,只不过需要注意一个特殊情况就是在删除队头的操作可能会有些区别。
/**
* 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 temp = head;
int length = 1;
while(temp.next != null){ //获得链表长度
temp = temp.next;
length++;
}
int local = length - n ; //获取正向的位置
if( local ==0)
return head.next; //若是第一个数,则直接返回后面的
int time = 1;
temp =head;
while(time<local){
temp = temp.next; //找到待删去节点的前一个的位置
time++;
}
temp.next = temp.next.next; //改变next的指针
return head;
}
}
还是第一次自己写的有这个效果,太感动了!