链表的合并与反转

来源:互联网 发布:蜂窝移动数据当期时间 编辑:程序博客网 时间:2024/06/05 08:28

将两个递增的链表合并为一个递增的链表,然后将这个链表反转


第一行输入一个数n,第二行输入n个递增的数,第三行输入m,再输入m个数,最后输出这n+m个数的递增的链表与递减的

代码如下:


#include <iostream>#include <cstdio>#include <algorithm>#include <vector>#include <cstring>#include <map>#include <cmath>#include <string>#include <queue>#include <stack>#include <math.h>using namespace std;const int N = 905;typedef struct LNode{double data;LNode *next;}LNode, *LinkList;//LinkList p;void InitList(LinkList L){L = new struct LNode;L->next = NULL;}void InitList( LinkList L,int n,double an[]){LinkList p, s;L->next = NULL;//L = new struct LNode;p = L;for (int i = 1; i <= n; i++){s = new LNode;s->data = an[i];p->next = s;p = s;p->next = NULL;}}void ListInsert(LinkList &L, int i, double e){LinkList p, s;int j;p = L;j = 0;while (p && (j < i-1 )){p = p->next; j++;}if (!p || j > i - 1)return;//ERROR;s = new LNode;s->data = e;s->next = p->next;p->next = s;return;//OK}void printf(LinkList L){LinkList p1;p1 = L;while ( p1->next!=NULL){p1 = p1->next;cout << p1->data << " ";}cout << endl;}void hebin(LinkList L1, LinkList L2){LinkList p1, p2;p1 = L1->next;p2 = L2->next;int i;i = 1;while ( p2 != NULL){p1 = L1->next;i = 1;while (p1 != NULL&&p1->data < p2->data&&p1 != NULL){i++;p1 = p1->next;}ListInsert(L1, i, p2->data);p2 = p2->next;}}void nizhuan(LinkList L1, LinkList L2){if (L1->next == NULL){L2->next = L1;return;}nizhuan(L1->next,L2);(L1->next)->next = L1;L1->next = NULL;return;}int main(){double an[5000];int n;int i;double a;LinkList L1, L2, L3;L1 = new LNode;L2 = new LNode;L3 = new LNode;while (cin >> n){for (i = 1; i <= n; i++){cin >> an[i];}InitList(L1, n, an);cin >> n;for (i = 1; i <= n; i++){cin >> an[i];}InitList(L2, n, an);//cout << L1->data << endl;printf(L1);printf(L2);//cout << "0asd\n";hebin(L1, L2);//cout << "1asd\n";printf(L1);nizhuan(L1->next, L1);printf(L1);}return 0;}

原创粉丝点击