C语言-链表建立、合并、打印

来源:互联网 发布:3tier数据 编辑:程序博客网 时间:2024/06/08 00:20

  问题:已知用两个单链表分别存储的两个字符串,均按递增次序排列。编程实现将这两个单链表归并为一个按数据域值递减次序排列的单链表。  
  要求:
   1) 单链表中每个结点只存放一个字符  
  2) 利用原链表中的结点空间存储归并后的单链表,不另外生成新链表   
  3) 单链表的建立写一函数create实现   
  4) 两个链表归并过程写一函数sub实现
  5) 输出结果写一函数output实现
  6) 主函数调用这三个函数完成程序功能

#include <stdio.h>#include <string.h>#include <stdlib.h>#define LEN sizeof(struct str)struct str{    char s;    struct str *next;};typedef struct str STR;STR *creat(char *string){    STR *head=NULL;    STR *prev,*current;    char *p=string;    while(*(string)!='\0')    {        current=(STR *)malloc(LEN);        if(head==NULL)            head=current;        else            prev->next=current;        current->s=*(string);        string++;        current->next=NULL;        prev=current;    }    return head;}void output(STR *head){       STR * p=head;    printf("the string is:\n");    if(head!=NULL)        do        {            printf("%c",p->s);            p=p->next;        }while(p!=NULL);}void sub(STR *a,STR *b){    STR *p1,*p2,*q;    char temp;    p1=a;p2=b;    while(p1->next)    {        p1=p1->next;    }    p1->next=p2;    p1=a;    while(p1->next)    {           q=p1->next;        while(q)        {            if(q->s<p1->s)            {                temp=q->s;                q->s=p1->s;                p1->s=temp;            }            q=q->next;              }        p1=p1->next;    }}int main(){      char a[]="I am a student!";    char b[]="where are you form?";    STR  *p1,*p2;    p1=creat(a);    p2=creat(b);    sub(p1,p2);    output(p1);    putchar('\n');    output(p2);    putchar('\n');}
原创粉丝点击