第五天 链表中倒数第k个结点
2016-07-27 08:39
288 查看
单链表对于我来说还是理论大于实现,趁这次机会掌握一下,包括创建,遍历以及逆序。
思路:1. 顺序下去,维持一个大小为k的矩阵,到结尾处输出矩阵第一个元素; 2. 逆序(需要两次,否则最后输出的是修改过的指针);3. 野生大神的解法,用两个指针相隔k-1距离顺序一遍搞定。
终于成功之后仍不住要吐个槽,连自相矛盾的样例都给,真是刷新了三观。
上自己的解法:
大神解法:
自己实现的单链表功能:
思路:1. 顺序下去,维持一个大小为k的矩阵,到结尾处输出矩阵第一个元素; 2. 逆序(需要两次,否则最后输出的是修改过的指针);3. 野生大神的解法,用两个指针相隔k-1距离顺序一遍搞定。
终于成功之后仍不住要吐个槽,连自相矛盾的样例都给,真是刷新了三观。
上自己的解法:
class Solution { public: ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) { if (!pListHead || k <= 0) return NULL; else { vector<ListNode*> node; int num = 1; ListNode *p = pListHead->next; node.push_back(pListHead); while(p) { num ++; if (node.size() == k) node.erase(node.begin()); node.push_back(p); p = p->next; } if (num < k) return NULL; return node[0]; } } };
大神解法:
public class Solution { public ListNode FindKthToTail(ListNode head,int k) { if(head==null||k<=0){ return null; } ListNode pre=head; ListNode last=head; for(int i=1;i<k;i++){ if(pre.next!=null){ pre=pre.next; }else{ return null; } } while(pre.next!=null){ pre = pre.next; last=last.next; } return last; } }
自己实现的单链表功能:
#include <vector> #include <iostream> using namespace std; struct ListNode { int val; struct ListNode *next; ListNode(int x) :val(x), next(NULL) {} }; ListNode* createList(int depth) { ListNode* head = (ListNode*)malloc(sizeof(ListNode)); ListNode *pre = head; int i = 0; while(i++ < depth - 1) { // 这里的内存会不会泄漏 ListNode* p = (ListNode*)malloc(sizeof(ListNode)); pre->next = p; pre->val = i; pre = p; } pre->val = depth; pre->next = NULL; return head; } void printList(ListNode *head) { if (!head) cout << "NULL" << endl; else { cout << head->val << "->"; ListNode *temp = head->next; while (temp) { cout << temp->val << "->"; temp = temp->next; } cout << "NULL" << endl; } } ListNode* reverseList(ListNode *head) { if (!head) return NULL; else { ListNode *p = head->next, *pre = head; head->next = NULL; while(p) { head = p; p = p->next; head->next = pre; pre = head; } return head; } } int main( ) { ListNode* head = createList(5); printList(head); head = reverseList(head); printList(head); return 0; }
相关文章推荐
- postgres log文件的位置
- 学习java的这一个月感悟
- So you've been rejected, now what? On appeals in peer-reviewed publications(From Wiley Exchanges)
- First code book 2章
- CodeForces 540A Combination Lock
- [置顶] 简单C/S系统(线程池+心跳检测+多线程+滚动日志)
- .NET Core的文件系统[2]:FileProvider是个什么东西?
- Spring MVC 学习总结(五)——校验与文件上传
- Java容器类源码-ArrayList的最全的源码分析
- leetcode 98 Validate Binary Search Tree (python)
- JAVA(四)java基本的数据类型,运算符
- linux pc-lint强大的静态代码检查工具
- windows下面安装Python和pip终极教程
- perl script.pl vs perldoc script.pl
- [Cloud Computing]Mechanisms: Threat Intelligence System
- PC LINT 错误信息禁止选项说明
- HDU5752 Sqrt Bo
- pclint之检查多个代码文件和库头文件
- string 分割字符串
- 拖拖看小游戏