首页 > 其他 > 详细

19. Remove Nth Node From End of List

时间:2020-02-13 19:44:16      阅读:42      评论:0      收藏:0      [点我收藏+]

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

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.

Follow up:

Could you do this in one pass?

 

 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 class Solution {
10     public ListNode removeNthFromEnd(ListNode head, int n) {
11         System.out.println(head.val);
12         if (head == null || head.next == null) return null;
13         
14         ListNode p1 = head;
15         for (int i = 0; i < n; ++i) {
16            
17             p1 = p1.next;
18         }
19         if (p1 == null) return head.next;
20         
21         ListNode p2;
22         for (p2 = head; p1.next != null; p1 = p1.next) {
23             p2 = p2.next;
24         }
25         p2.next = p2.next.next;
26         return head;
27     }
28 }

 

19. Remove Nth Node From End of List

原文:https://www.cnblogs.com/hyxsolitude/p/12304800.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!