zoukankan      html  css  js  c++  java
  • 归并链表

     1 #include<iostream.h>
    2 #include<malloc.h>
    3 struct node
    4 {
    5 int data;
    6 struct node *next;
    7 };
    8 void traverse_list(struct node *head)
    9 {
    10 int i = 1;
    11 struct node *p;
    12 p = head->next;
    13 while(p)
    14 {
    15 if(i != 1)
    16 cout<<' ';
    17 cout<<p->data;
    18 p = p->next;
    19 i++;
    20 }
    21 cout<<endl;
    22 }
    23 struct node *creat(int k)
    24 {
    25 struct node *head,*p,*tail;
    26 head = (struct node *)malloc(sizeof(struct node));
    27 head->next = NULL;
    28 tail = head;
    29 while(k--)
    30 {
    31 p = (struct node *)malloc(sizeof(struct node));
    32 cin>>p->data;
    33 p->next = NULL;
    34 tail->next = p;
    35 tail = p;
    36 }
    37 return head;
    38 }
    39 void merge(struct node *head1,struct node *head2)
    40 {
    41 struct node *p,*q,*tail;
    42 p = head1->next;
    43 q = head2->next;
    44 tail = head1;
    45 while(p&&q)
    46 {
    47 if(p->data<q->data)
    48 {
    49 tail->next = p;
    50 tail = p ;
    51 p = p->next;
    52 }
    53 else
    54 {
    55 tail->next = q;
    56 tail = q;
    57 q = q->next;
    58 }
    59 }
    60 if(p)
    61 tail->next = p;
    62 else
    63 tail->next = q;
    64 traverse_list(head1);
    65 }
    66 int main()
    67 {
    68 int m, n;
    69 struct node *head1,*head2;
    70 cin>>m>>n;
    71 head1 = creat(m);
    72 head2 = creat(n);
    73 merge(head1,head2);
    74 return 0;
    75 }
  • 相关阅读:
    面向对象--进阶
    组合补充--类的特殊成员
    面向对象--类,嵌套
    面向对象(初级)
    模块--包
    异常处理
    模块--3
    模块--2
    django环境处理
    Django使用中间件通过CORS方式解决跨域
  • 原文地址:https://www.cnblogs.com/shangyu/p/2345691.html
Copyright © 2011-2022 走看看