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

来源:互联网 发布:消费宝集团 知乎 编辑:程序博客网 时间:2024/04/27 20:52

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

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

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

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

/** * 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        //判断链表是否为空 or n值为0        if(head == null || n == 0){            return null;        }        ListNode fast = head;        ListNode dummy = new ListNode(0);        dummy.next = head;        ListNode slow = dummy;        for(int i=0;i<n-1;i++){            //进行判断防止n大于链表的长度            if(fast.next!=null){                fast=fast.next;            }else{                return null;            }        }        while(fast.next!=null){            fast=fast.next;            slow=slow.next;        }        slow.next=slow.next.next;        return dummy.next;    }}



0 0
原创粉丝点击