LeetCode刪除連結串列中倒數第n個結點
阿新 • • 發佈:2018-12-11
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.
class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { ListNode a = head; ListNode b = head; ListNode c = head; for(int i=0; i<n; i++){ b = b.next; } if(b == null){ return a.next; } while(b.next != null){ b = b.next; c = c.next; } if(c.next.next == null){ c.next = null; }else{ c.next = c.next.next; } return a; } }