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

LeetCode: Remove Nth Node From End of List

一次过

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode *removeNthFromEnd(ListNode *head, int n) {
12         // Start typing your C/C++ solution below
13         // DO NOT write int main() function
14         vector<ListNode *> S;
15         ListNode *tmp = head;
16         while (tmp) {
17             S.push_back(tmp);
18             tmp = tmp->next;
19         }
20         S.push_back(NULL);
21         int size = S.size();
22         if (size < n+2) return head->next;
23         S[size-n-2]->next = S[size-n];
24         return head;
25     }
26 };

 C#

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     public int val;
 5  *     public ListNode next;
 6  *     public ListNode(int x) { val = x; }
 7  * }
 8  */
 9 public class Solution {
10     public ListNode RemoveNthFromEnd(ListNode head, int n) {
11         List<ListNode> S = new List<ListNode>();
12         ListNode tmp = head;
13         while (tmp != null) {
14             S.Add(tmp);
15             tmp = tmp.next;
16         }
17         S.Add(null);
18         int c = S.Count;
19         if (c < n + 2) return head.next;
20         S[c - n - 2].next = S[c - n];
21         return head;
22     }
23 }
View Code

 

posted @ 2013-04-20 06:33  ying_vincent  阅读(130)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3