leetcode-19-Remove Nth Node From End of List
来源:互联网 发布:淘宝简明英语语法教程 编辑:程序博客网 时间:2024/06/06 03:03
问题
题目:[leetcode-19]
思路
需要注意一点,当n==len的情形需要特殊处理。
代码
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode* removeNthFromEnd(ListNode* head, int n) { int len = 0; for( ListNode* p = head; p!=NULL; p=p->next ) len++; if(n==len) { ListNode* p = head; head = head->next; delete p; p = NULL; return head; } int cnt = len-n; ListNode* pre = NULL; ListNode* p = head; for(int i = 0; i < cnt; ++i){ pre = p; p=p->next; } pre->next = p->next; delete p; p = NULL; return head; }};
思路1
本省可以两个指针。但是边界情况太多。
所以,先算出节点个数了。
边界情况比较多,小心!
代码1
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode* removeNthFromEnd(ListNode* head, int n) { if(!head) return NULL; // 1 ListNode* p = head; int cnt = 0; while(p){ ++cnt; p = p->next; } if(cnt < n) return NULL; // 2 if(1==cnt) return NULL; // 3 if(n==cnt){ // 4 ListNode* ret = head->next; delete head; return ret; } int k = cnt - n - 1; std::cout << k << std::endl; p = head; for(int i = 0; i < k; ++i){ p = p->next; } ListNode* q = p->next; p->next = q->next; delete q; return head; }};
0 0
- [Leetcode]LeetCode 19:Remove Nth Node From End of List
- Leetcode 19 Remove Nth Node From End of List
- LeetCode 19: Remove Nth Node From End of List
- [Leetcode 19, Easy] Remove Nth Node From End of List
- LeetCode(19) Remove Nth Node From End of List
- [LeetCode 19] Remove Nth Node From End of List Solutions
- leetcode 19 Remove Nth Node From End of List
- Leetcode【19】:Remove Nth Node From End of List
- [leetcode 19] Remove Nth Node From End of List
- [Leetcode] 19 - Remove Nth Node From End of List
- LeetCode | #19 Remove Nth Node From End of List
- leetcode.19----------Remove Nth Node From End of List
- [Leetcode 19, Easy] Remove Nth Node From End of List
- LeetCode 19 Remove Nth Node From End of List
- leetcode-19 Remove Nth Node From End of List
- leetCode #19 Remove Nth Node From End of List
- leetcode 19 Remove Nth Node From End of List
- leetcode 19 Remove Nth Node From End of List
- Windows系统结构图
- 欢迎使用CSDN-markdown编辑器
- 栈
- CSS选择器
- 25个经典的Spring面试问答
- leetcode-19-Remove Nth Node From End of List
- Linux下图形函数库---curses.h
- GridView smoothScrollBy移动距离不正确
- 视音频编解码基本术语及解释
- 数据访问的一些笔记
- The Dole Queue(子过程设计)(UVa 133)
- 算法题
- .net MVC中Jquery实现AJAX详解
- Linux下图形函数库2---curses.h