• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode: Remove Nth Node From End of List

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.

 

 这道题要注意的Corner Case是:如果n比这个LinkedList的size大,那么就需要直接返回Head,如果相等,就把head删掉,返回head.next;基本做的方法呢,还是Runner Technique. 由于有可能head会被删掉,所以最好还是使用一个dummy node,dummy.next = head。

 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         ListNode dummy = new ListNode(-1);
12         dummy.next = head;
13         ListNode p1 = dummy, p2 = dummy;
14         while (p2.next != null) {
15             if (n > 0) {
16                 n --;
17             }
18             else p1 = p1.next;
19             p2 = p2.next;
20         }
21         if (n == 0) p1.next = p1.next.next;
22         return dummy.next;
23     }
24 }

 

 

posted @ 2014-05-09 04:55  neverlandly  阅读(375)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3