带头节点单链表的合并及相关操作

来源:互联网 发布:山内一丰数据 编辑:程序博客网 时间:2024/05/17 16:15
 
//带头节点的链表操作 #include <iostream>#include <cstdio>#include <cstdlib>using namespace std;typedef  struct List{int data;struct List *next;}List,*list;void ListInit(list &L){list p = L = NULL;}list CreatList(){    list head = (list)malloc(sizeof(list));    head->next = NULL;     list p,t;    int a ;    while(scanf("%d",&a)){        if(a!=0){                t=(list)malloc(sizeof(struct List));                t->data=a;                if(head->next==NULL){                     head->next = t;                }                else{                     p->next=t;                }                p=t;        }        else{            p->next=NULL;     //一定要有此部分结束,否则传值无底线            break;        }    }        return head;}int Lengthlist(list &L){list p = L;int length = 0;while(p){length++;p = p->next;}return length;}void  ListInsert(list L, int location, int value){     list p = L;     int j  = 0;      //寻找第location-1个元素位置      while(p&&j<location-1){     p = p->next;     j++;}     if(!p||j>=location){     printf("插入错误!!\n");     return;}     list item = (list)malloc(sizeof(list));     item->data  = value;     item->next = p->next; p->next = item; } int  ListDelete(list &L,int location){     int flag = 1;     //判断是否成功删除  list p1 = L; list p2 = L->next;     int  j  = 0;      //删除第location个元素位置  while(p2&&j<location-1){     p1 = p2;     p2 = p1->next;     j++;     }    if(!p2||j>=location){         flag = 0;            return flag;exit(0);        }    p1->next = p2->next;        free(p2);        return flag;}list MergeList(list a,list b){list la = a->next,lb = b->next;list c,lc;lc = c = a;            //lc取a的地址 while(la&&lb){if(la->data<=lb->data){ c->next = la ; c = la; la = la->next;}else{    c->next = lb; c = lb;  lb = lb->next;}}    c->next = la?la:lb;    return  lc;         // 返回新表c的头节点 }void  PrintList(list &L){    list p = L->next;    while(p!=NULL){      printf("%d ",p->data);      p = p->next;    }}int main(int argc, char** argv) {    list c;            printf("输入两个链表均以0结束!\n");    list a = CreatList();     //a链表list b = CreatList();    //b链表    list d = MergeList(a,b);    PrintList(d);       printf("\n");    int k = ListDelete(d,10);    if(k){    printf("删除成功...\n");     PrintList(d);}else{printf("删除失败!!!...\n"); PrintList(d);}//测试 //    ListInsert(b,4,100);//    printf("\n");//    PrintList(b);return 0;}

原创粉丝点击