remove-nth-node-from-end-of-list

/**
* 給定一個鏈表,刪除鏈表的倒數第n個節點並返回鏈表的頭指針
* 例如,
* 給出的鏈表爲:1->2->3->4->5, n= 2.↵↵
* 刪除了鏈表的倒數第n個節點以後,鏈表變爲1->2->3->5.
* 備註:
* 題目保證n必定是合法的
* 請嘗試只用一步操做完成該功能
*/

/**
 * 給定一個鏈表,刪除鏈表的倒數第n個節點並返回鏈表的頭指針
 * 例如,
 *    給出的鏈表爲:1->2->3->4->5, n= 2.↵↵
 *    刪除了鏈表的倒數第n個節點以後,鏈表變爲1->2->3->5.
 * 備註:
 * 題目保證n必定是合法的
 * 請嘗試只用一步操做完成該功能
 */

public class Main58 {
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);
        System.out.println(Main58.removeNthFromEnd(head, 2).val);
    }

    public static class ListNode {
        int val;
        ListNode next;
        ListNode(int x) {
            val = x;
            next = null;
        }
    }

    public static ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode first = head;
        ListNode second = head;
        while (n-- > 0) {
            first = first.next;
        }
        ListNode pre = null;
        while (first.next != null) {
            pre = second;
            second = second.next;
            first = first.next;
        }
        if (pre != null) {
            pre.next = second.next;
        }else{
            head = head.next;
        }
        return head;
    }
}
本站公眾號
   歡迎關注本站公眾號,獲取更多信息