连接两个排序的单链表
2016-03-31 16:57
225 查看
牛客中的代码是这样的:
两个唯一的不同是在那个新链表的表头,重新申请的空间,牛客中的初始化一定要看结构体中是如何说的,很明显,按牛客给出的结构体中,对于节点的初始化时需要显式调用构造函数,而vS中的是人为初始化,这就是,用这种方法,牛客编译不通过的唯一原因
struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } }; ListNode* Merge(ListNode* pHead1, ListNode* pHead2) { if (pHead1 == NULL && pHead2 == NULL) { return NULL; } if (pHead1 == NULL || pHead2 == NULL) { return pHead1 == NULL ? pHead2 : pHead1; } ListNode* ppHead1 = pHead1; ListNode* ppHead2 = pHead2; ListNode* newHead = new ListNode(0); ListNode* cur = newHead; while (ppHead1 && ppHead2) { if (ppHead1->val < ppHead2->val) { cur->next = ppHead1; ppHead1 = ppHead1->next; } else { cur->next = ppHead2; ppHead2 = ppHead2->next; } cur = cur->next; } if (ppHead1 == NULL) { cur->next = ppHead2; } if (ppHead2 == NULL) { cur->next = ppHead1; } return newHead->next; }vs中的代码是这样的:
#pragma once #include<assert.h> #include<iostream> using namespace std; typedef int DataType; //结构体 链表 typedef struct ListNode { DataType data; struct ListNode *next; }ListNode; //初始化链表 void InitList(ListNode** pHead) { *pHead = NULL; } //插入节点//尾插法 void Insert(ListNode*& pHead, DataType x) { if (pHead == NULL) { pHead = new ListNode[sizeof(ListNode)]; pHead->data = x; pHead->next = NULL; } else { ListNode* tial = pHead; ListNode* pos = new ListNode[sizeof(ListNode)]; while (tial->next != NULL) { tial = tial->next; } pos->data = x; tial->next = pos; pos->next = NULL; } } //遍历单链表 void PrintList(ListNode* pHead) { ListNode* cur = pHead; assert(pHead); while (cur) { cout << cur->data << "->"; cur = cur->next; } cout << "NULL" << endl; } //翻转单链表 ListNode* Revers(ListNode* pHead) { ListNode* newhead = NULL; ListNode* cur = pHead; while (cur) { ListNode* tmp = cur; cur = cur->next; tmp->next = newhead; newhead = tmp; } return newhead; } //合并两个单链表 ListNode* Merge(ListNode*& pHead1, ListNode*& pHead2) { if (pHead1 == NULL && pHead2 == NULL) { return NULL; } if (pHead1 == NULL || pHead2 == NULL) { return pHead1 == NULL ? pHead2 : pHead1; } ListNode* ppHead1 = pHead1; ListNode* ppHead2 = pHead2; ListNode* newHead = new ListNode[sizeof(ListNode)]; ListNode* cur = newHead; while (ppHead1 && ppHead2) { if (ppHead1->data < ppHead2->data) { cur->next = ppHead1; ppHead1 = ppHead1->next; } else { cur->next = ppHead2; ppHead2 = ppHead2->next; } cur = cur->next; } if (ppHead1 == NULL) { cur->next = ppHead2; } if (ppHead2 == NULL) { cur->next = ppHead1; } return newHead->next; }
两个唯一的不同是在那个新链表的表头,重新申请的空间,牛客中的初始化一定要看结构体中是如何说的,很明显,按牛客给出的结构体中,对于节点的初始化时需要显式调用构造函数,而vS中的是人为初始化,这就是,用这种方法,牛客编译不通过的唯一原因
相关文章推荐
- Plist—ios应用数据存储方式
- 15个数从大到小排列
- 小波工具箱的使用2
- /*+ 提示信息*/ 常用hint oracle
- java 中jdbc 链接数据库
- ECNU OJ
- 这叫啥事
- 连接两个排序的单链表
- audio元素和video元素在ios和andriod中无法自动播放
- Socket心跳包机制
- [IOS 开发] Autolayout约束动画化
- 好厉害的库edge.js!实现C#与node.js互操作
- ZeroMQ 简单的高性能REP-REQ模型,Java语言版本
- FastDFS 5.08 tracker.conf配置文件详细说明
- 自定义Visual Assist X Snippets 宏
- 回避测试
- 计时器的制作
- 一句话设计模式
- Android设置透明、半透明等效果
- vb老师讲的出随机数法