leetcode Remove Nth Node From End of List

来源:互联网 发布:安卓运行ubuntu 编辑:程序博客网 时间:2024/05/18 05:34

双指针大法又显神通。


/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {    public ListNode removeNthFromEnd(ListNode head, int n) {         if(head==null)return null; ListNode ret=new ListNode(-1); ret.next=head; ListNode p1=ret; ListNode p2=ret; int i=0; while(i<n&&p2.next!=null){ p2=p2.next; i++; } if(p2==null&&i!=n)return head; while(p2.next!=null){ p1=p1.next; p2=p2.next;  } p1.next=p1.next.next; return ret.next;           }}

0 0
原创粉丝点击