LeetCode 16 Remove Nth Node From End of List

方法一: 双指针容易点。

 

 1 public class Solution {
 2   public ListNode removeNthFromEnd(ListNode head, int n) {
 3     // Write your solution here
 4     if (head == null) {
 5       return head; 
 6     }
 7     
 8     if (n > getNum(head)) {
 9      return head; 
10     }
11     
12     ListNode dummy = new ListNode(0);
13     dummy.next = head;
14     ListNode fast = dummy, slow = dummy;
15     for (int i = 0; i <= n; i++) {
16       fast = fast.next; 
17     }
18     
19     while (fast != null) {
20       fast = fast.next;
21       slow = slow.next;
22     }
23     slow.next = slow.next.next;
24     return dummy.next;
25   }
26   
27   private int getNum(ListNode head) {
28     int count = 0;
29     while (head != null) {
30       count++;
31       head = head.next; 
32     }
33     return count;
34   }
35 }

 

方法二: 数个数

 

 1 public ListNode removeNthNode(ListNode head, int n) {
 2 // Should using dummy node here because n may remove the head node.So we must keep the head.
 3 if (head == null || n == 0) {
 4     return head;
 5 }
 6 
 7 ListNode dummy = new ListNode(0);
 8 dummy.next = head;
 9 ListNode cur = dummy;
10 
11 ListNode fast = head;
12 ListNode slow = head;
13 
14 // Firstly, count the length of the linked list
15 int len = 1;
16 while(fast.next != null && fast.next.next != null) {
17     fast = fast.next.next;
18     slow = slow.next;
19     len++;
20 }
21 //          1  2  3  4  5  6  7  8 null   , for n = 5
22 //  dummy             n
23 if (fast.next == null) {
24     len = 2 * len - 1;
25 } else if (fast.next.next == null) {
26     len = 2 * len;
27 }
28     
29 // Calculate the difference of length: 8 - 5 = 3
30 int pos = len - n;
31 
32 // If we use the dummy node, then the i must start from i = 0;
33 for (int i = 0; i < pos; i++) {
34     cur = cur.next;
35 }
36 // cur points to 3, we need to delete 4
37 cur.next = cur.next.next;
38 return dummy.next;
39 }

 

转载于:https://www.cnblogs.com/mayinmiao/p/8492558.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值