删除链表中倒数第n个节点

来源:互联网 发布:ubuntu配置jdk1.8 编辑:程序博客网 时间:2024/06/11 21:48

删除链表中倒数第n个节点

15:00

给定一个链表,删除链表中倒数第n个节点,返回链表的头节点。


 注意事项

链表中的节点个数大于等于n

给出链表1->2->3->4->5->null和 n = 2.

删除倒数第二个节点之后,这个链表将变成1->2->3->5->null.

利用两个节点

 ListNode removeNthFromEnd(ListNode head, int n) {        if (head == null || n<0) return head;        ListNode myhead = head;        ListNode tail = head;        while (n>0 && tail.next != null) {            tail = tail.next;            n--;        }        if (n>1) return head;        if (n==1 && tail.next == null) return head.next;        while (tail.next != null) {            myhead = myhead.next;            tail = tail.next;        }        myhead.next = myhead.next.next;        return head;    }


1 0
原创粉丝点击