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;}


原创粉丝点击