24.链表的逆置与合并
来源:互联网 发布:明基显示器知乎 编辑:程序博客网 时间:2024/05/29 03:49
题目:
1、对一个链表进行就地逆置
2、对两个有序链表进行合并,合并为一个有序链表
答案:
//20130130
#include <iostream>using namespace std;typedef struct node {int num;node* next;}node,*pnode;pnode makeList(const int s[],int n);void printList(const pnode p);int inverseList(const pnode p);pnode mergeList(const pnode a, const pnode b);int main(){int a[10] = {10,20,30,40,50,60,70,80,90,100};int b[10] = {9,11,22,23,45,67,79,101,102,103};//链表就地逆置//生成链表,带表头pnode pn = makeList(a,10);printList(pn);int n=inverseList(pn);cout<<endl;printList(pn);cout<<endl;//两个链表合并,生成有序链表pnode p1 = makeList(a,10);pnode p2 = makeList(b,10);pnode p=mergeList(p1,p2);printList(p);return 0;}pnode makeList(const int s[], int n){pnode pre = NULL;pnode head=new node;head->num = -1;pre = head;for (int i = 0;i < n;i++){pnode p=new node;p->num=s[i];pre->next = p;pre = p;}pre->next = NULL;return head;}int inverseList(const pnode p){pnode head = p->next;pnode now = head->next;head->next = NULL;pnode last = now->next;while (last != NULL){now->next = head;head = now;now = last;last = last->next;}now->next = head;p->next = now;return 0;//返回0,表示成功}void printList(const pnode p){pnode tmp = p->next;while (tmp !=NULL){cout<<tmp->num<<",";tmp = tmp->next;}}pnode mergeList(const pnode a, const pnode b){pnode head = new node;pnode p1 = a->next;pnode p2 = b->next;if (p1->num > p2->num){head->next = p2;p2 = p2->next;}else{head->next = p1;p1 = p1->next;}pnode tmp = head->next;while (p1 != NULL && p2 != NULL){if (p1->num > p2->num){tmp->next = p2;p2 = p2->next;}else{tmp->next = p1;p1 = p1->next;}tmp = tmp->next;}if (p1 !=NULL){tmp->next = p1;}if (p2 != NULL){tmp->next = p2;}return head;}
- 24.链表的逆置与合并
- 链表的生成与合并
- 链表的合并与排序
- 链表的合并与反转
- 第二章 线性表(链表的建立与合并)
- 链表的合并
- 链表的合并
- 链表的合并
- Linkedlist 索引+链表的合并与删除
- 合并两个有序链表的递归与非递归
- 逆转交替合并两个链表的解析与实现
- 两个有序链表的合并与交集
- 链表的逆置、合并、排序以及插入删除
- 合并查询结果 与 表的别名
- 合并有序的链表
- 链表的合并 源码
- 一种链表的合并
- 两个链表的合并
- Android之监听文件和目录动态
- 读取Weblogic数据源
- Delphi xe3 下配置 MAC OS X 编程调试模式
- 大数据,职场和商业运作的角度
- 转 linux如何查看系统信息
- 24.链表的逆置与合并
- python中json.dumps打印出u字符
- Gnome Shell学习笔记——Gnome Shell是什么
- 工作笔记:web service中使用linq 动态增减返回字段
- java对象的生命周期
- Shell编程入门
- JAVA关键字this
- WP7 Isolated Storage 系列 - 5.使用XmlSerializer读取和存储XML文件
- Final关键字(修饰变量)