LeetCode_OJ【19】Remove Nth Node From End of List

来源:互联网 发布:移动老用户优惠淘宝 编辑:程序博客网 时间:2024/06/08 09:48

Given a linked list, remove the nth node from the end of list and return its head.

For example,

   Given linked list: 1->2->3->4->5, and n = 2.   After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:
Given n will always be valid.
Try to do this in one pass.

一次遍历删除链表中倒数第N个元素。

思路很简单,设置两个指针p,q,中间间隔n-1个元素,当q指向链表结尾时,需要删除的元素正好是p的下一个元素。

在写算法的时候还是碰到了一些问题,比如有些测试用例需要删除的就是头结点,这种情况应该怎么处理呢,

后来参考了别人一些写法,在head结点前面设置dummy结点,算法结束后直接返回dummy.next即可。

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode removeNthFromEnd(ListNode head, int n) {        ListNode dummy = new ListNode(-1);dummy.next = head;ListNode p = dummy, q = dummy;for (int count = 1; q.next != null; q = q.next, count++) {if (count > n)p = p.next;}p.next = p.next.next;return dummy.next;    }}


0 0
原创粉丝点击