Given a linked list, remove the nth node from the end of list and return its head.題目要求輸入一個linked list 和一個數字n。要求咱們返回刪掉了倒數第n個節點的鏈表。node
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.指針
public ListNode removeNthFromEnd(ListNode head, int n) { ListNode start = new ListNode(0); ListNode slow = start , fast = start; slow.next = head; //使fast點和slow點的差距爲n for(int i=1;i<=n+1;i++){ fast = fast.next; } //同時移動fast和slow 使得fast到達listnode的末尾 while(fast != null){ slow = slow.next; fast = fast.next; } //刪除倒數第n個節點 slow.next = slow.next.next; return start.next; }