美文网首页
2019-07-29 ListNoderemoveNthFro

2019-07-29 ListNoderemoveNthFro

作者: mister_eric | 来源:发表于2019-07-29 07:55 被阅读0次

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

    示例:

    给定一个链表: 1->2->3->4->5, 和 n = 2.

    当删除了倒数第二个节点后,链表变为 1->2->3->5.

    说明:

    给定的 n 保证是有效的。

    进阶:

    你能尝试使用一趟扫描实现吗

    来源:力扣(LeetCode)

    链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list

    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    package com.tao.top_100_liked_questions;

    import com.tao.comm.ListNode;

    import com.tao.comm.Utils;

    public class _19_removeNthFromEnd {

    public static void main(String[] args){

    ListNode list = Utils.createList(new int[]{1, 2, 3, 4, 5});

            Utils.printList(list);

            ListNode removeNthFromEnd =removeNthFromEnd(list, 2);

            Utils.printList(removeNthFromEnd);

        }

    public static ListNoderemoveNthFromEnd(ListNode head,int n){

    ListNode dummy =new ListNode(0);

            dummy.next = head;

            ListNode first = dummy;

            ListNode second = dummy;

            for (int i =0; i <= n; i++){

    first = first.next;

            }

    System.out.println("first : " + first.val);

            while (first!=null) {

    first = first.next;

                second = second.next;

            }

    System.out.println("second : " + second.val);

            second.next = second.next.next;

            return dummy.next;

        }

    }

    相关文章

      网友评论

          本文标题:2019-07-29 ListNoderemoveNthFro

          本文链接:https://www.haomeiwen.com/subject/uncvrctx.html