LeetCode -- Remove Nth Node from End of List
Question:
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.
Note:
Given n will always be valid.
Try to do this in one pass.
Analysis:
给出一个链表,移走从链表的末尾数起第n个节点,然后返回原来链表的链首。注意:n一般来说是有效的,尝试只遍历链表一次解决问题。
首先遍历一遍链表,得出链表的总长度。然后删除从最末数的第n个节点,也就是删除从头结点数起的第len+1-n个节点,这样,只需找到第len-n个节点,然后删除他后面的一个节点即可。注意只有一个节点而且n=1的情况;删除首节点的情况;删除最后节点的情况等。
Answer:
/** * 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) { if(head == null) return head; if(n <= 0) return head; //先得到链表的长度 int len = 1; ListNode h = head; while(h.next != null) { h = h.next; len++; } if(n == 1 && head.next == null) //只有一个节点的情况 return null; if(n == 1) { //删除最后一个节点 h = head; while(h.next.next != null) { h = h.next; } h.next = null; return head; } if(n == len) { //删除第一个节点 h = head; head = head.next; h.next = null; return head; } int del = len - n; h = head; int i = 1; while(i < del) { h = h.next; i++; } h.next = h.next.next; return head; } }