LeetCode 19. Remove Nth Node From End of List

来源:互联网 发布:八皇后问题递归c语言 编辑:程序博客网 时间:2024/06/10 23:22

LeetCode 19. Remove Nth Node From End of List

给定一个链表,删除倒数第n各元素。
例如 给定链表: 1->2->3->4->5, and n = 2.

删除倒数第n各元素之后,剩下 1->2->3->5.

解题要求只遍历一次。

主要是利用两个指针之间的路程差为n来解这道题。

public ListNode removeNthFromEnd(ListNode head,int n){        ListNode temp = head;        ListNode result = head;        int num = 0;        while (head != null){            head = head.next;            if(num > n){                temp = temp.next;            }            num++;        }        if(n == num)            result = result.next;        else            temp.next = temp.next.next;        return result;    }