leetcode做题总结,题目Remove Nth Node From End of List 2012/01/27

来源:互联网 发布:js复选框全选 编辑:程序博客网 时间:2024/06/07 03:29

删除链表倒数第N的节点,也没什么难度,用两个指针相隔N个节点,然后同时向后移动,一个到末尾另一个就是第N个节点。

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {    public ListNode removeNthFromEnd(ListNode head, int n) {        ListNode newhead = new ListNode(0);        ListNode start = new ListNode(0);        ListNode end = new ListNode(0);        newhead.next = head;        end=newhead;        start=newhead;                for(int i=0;i<n;i++){            if(end.next!=null){                end=end.next;            }else                 return head;        }        while(end.next!=null){            end=end.next;            newhead=newhead.next;        }        newhead.next=newhead.next.next;        return start.next;    }}

Update 2015/08/28: 上面的题目一上来直接创建三个节点我就呵呵了。。也不知道当时是怎么想的。下面来个正常的吧

/** * Definition for ListNode. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int val) { *         this.val = val; *         this.next = null; *     } * } */ public class Solution {    /**     * @param head: The first node of linked list.     * @param n: An integer.     * @return: The head of linked list.     */    ListNode removeNthFromEnd(ListNode head, int n) {        // write your code here        if (n <= 0) {            return null;        }                ListNode start = new ListNode(0);        start.next = head;                ListNode p = start;        for (int i = 0; i < n; i++) {            if (head == null) {                return null;            }            head = head.next;        }        while (head != null) {            head = head.next;            p = p.next;        }        p.next = p.next.next;        return start.next;    }}


0 0