标签:init move list remove class int val head tor
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 //双指针法 10 class Solution { 11 public ListNode removeNthFromEnd(ListNode head, int n) { 12 if(null==head){ 13 return head; 14 } 15 ListNode iterator = head; 16 ListNode pre = null; 17 ListNode slowIterator = head; 18 int i=1; 19 while(iterator.next!=null){ 20 if(i==n){ 21 pre=head; 22 iterator=iterator.next; 23 slowIterator=slowIterator.next; 24 i++; 25 }else if(i<n){ 26 iterator=iterator.next; 27 i++; 28 }else{ 29 pre=slowIterator; 30 iterator=iterator.next; 31 slowIterator=slowIterator.next; 32 i++; 33 } 34 } 35 if(pre==null){ 36 return head.next; 37 }else{ 38 pre.next=slowIterator.next; 39 return head; 40 } 41 } 42 }
标签:init move list remove class int val head tor
原文地址:https://www.cnblogs.com/gongzixiaobaibcy/p/11908443.html