LeetCode 19. Remove Nth Node From End of List

来源:互联网 发布:淘宝投诉处理流程 编辑:程序博客网 时间:2024/05/29 19:46

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.

Subscribe to see which companies asked this question.


把一个单向链表的倒数第n个节点去掉。

这个题很简单的思路就是:先遍历一遍链表得到长度,找到第len-n+1个元素跳过即可:

/** * 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) {        int len = 0;        ListNode q = head;        while(q!=null){            q = q.next;            len++;        }        if(len==1||len==n){            return head.next;        }        ListNode p = head;        for(int i=0;i<len;i++){            if(i+n+1==len){                p.next = p.next.next;                break;            }            else p = p.next;        }        return head;    }}
而更简单的方法则是不需要获取长度,而是先找到正数第n个元素,并让一个指针指向它,另一个指针指向head,两个指针同时前进,直到第一个指针为null,此时跳过第二个指针的元素即可。

0 0
原创粉丝点击