经典算法——合并两个有序链表
2016-05-06 15:15
204 查看
题目描述
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.完整测试程序:
#include <iostream> using namespace std; struct ListNode { int val; ListNode* next; }; ListNode* MergeTwoSortedLists(ListNode* l1, ListNode* l2) { ListNode* newhead = NULL; ListNode* p = NULL; if (l1 == NULL) return l2; if (l2 == NULL) return l1; if (l1->val < l2->val){ newhead = l1; p = l1; l1 = l1->next; } else{ newhead = l2; p = l2; l2 = l2->next; } while (l1 && l2) { if (l1->val < l2->val) { p ->next= l1; l1 = l1->next; } else { p->next = l2; l2 = l2->next; } p = p->next; } p->next = l1 ? l1 : l2; return newhead; } ListNode* CreateListNode(int value) { ListNode* pNode = new ListNode(); pNode->val = value; pNode->next = NULL; return pNode; } void DestroyList(ListNode* pHead) { ListNode* pNode = pHead; while (pNode != NULL) { pHead = pHead->next; delete pNode; pNode = pHead; } } void ConnectListNodes(ListNode* pCurrent, ListNode* pNext) { if (pCurrent == NULL) { printf("Error to connect two nodes.\n"); exit(1); } pCurrent->next = pNext; } int main() { ListNode* pNode1 = CreateListNode(1); ListNode* pNode2 = CreateListNode(2); ListNode* pNode3 = CreateListNode(3); ListNode* pNode4 = CreateListNode(4); ListNode* pNode5 = CreateListNode(5); ListNode* pNode6 = CreateListNode(3); ListNode* pNode7 = CreateListNode(5); ConnectListNodes(pNode1, pNode2); ConnectListNodes(pNode2, pNode3); ConnectListNodes(pNode3, pNode4); ConnectListNodes(pNode4, pNode5); ConnectListNodes(pNode6, pNode7); ListNode* p1 = pNode1; ListNode* p6 = pNode6; cout << "链表l1: "; while (p1) { cout << p1->val << " "; p1 = p1->next; } cout << endl; cout << "链表l2: "; while (p6) { cout << p6->val << " "; p6 = p6->next; } cout << endl; ListNode* res = MergeTwoSortedLists(pNode1, pNode6); cout << "合并后链表: "; while (res) { cout << res->val << " "; res = res->next; } cout << endl; system("pause"); DestroyList(res); return 0; }
相关文章推荐
- SERVLETJSP学习(三)—— 容器对路径的处理 、Servlet特性
- java.lang.AbstractMethodError
- EventBus 3.0变化
- Failed to read artifact descriptor for org.apache.poi:poi-ooxml:pom.lastUpdated:3.10-FINAL
- stdafx.h预编译头
- 05056简单kvo
- bzoj 4553: [Tjoi2016&Heoi2016]序列
- Lua系统函数
- C#UDP通讯UdpClient
- [Android]ListView中分割线的设置
- NSIS自删除
- 限制一个或多个textfiled输入长度及内容
- xcode安装 插件
- shell 参数,shell与Java 交互参数
- viewPager的 transformPage方法中position含义
- http2
- nineoldandroids学习笔记
- nineoldandroids学习笔记
- MYSQL必知必会读书笔记 第十二和十三章 分组数据
- 扩展vbox硬盘大小