线性表的链式存储

今天开始写数据结构了,感觉不错!!2012-05-19

 

线性表的链式存储

 

Time Limit:   1000MS       Memory Limit:   65535KB
Submissions:   191       Accepted:   85

 

Description

建立长度为n的线性表的链表类LinList,长度n通过和n个数据元素通过cin输入。 要求: 1)调用Insert函数,建立长度为n的链表A, 2)建立长度为m的链表B,并编写函数实现单链表类LinList的对象B连接到单链表类LinList的对象A的尾部:Void Concatenate(LinList& A, LinList& B)。并输出链接后的链表的所有数据元素。

 

Input

输入共有四行,第一行是一个整数n,表示线性表A的长度; 第二行输入n个数据元素; 第三行是一个整数m,表示线性表B的长度; 第四行输入m个数据元素。

 

Output

输出A和B链接后的所有数据

 

Sample Input

 

5
1 2 3 4 5
6
11 22 33 44 55 66

 

Sample Output

 

1 2 3 4 5 11 22 33 44 55 66

 

 

# include<stdio.h>
# include<stdlib.h>
# include<malloc.h>
typedef struct node
{
    int num;
    struct node *next;
}SeqList;
SeqList *Insert(int n)//创建链表
{
    int t=0;
    SeqList *head,*p1,*p2;
    p1=p2=(SeqList *)malloc(sizeof(SeqList));
    head=NULL;
    if(n==0)return head;//n=0,返回NULL
    scanf("%d",&p1->num);
    head=p1;//这里很重要,解决n=1的情况
    while(t<n-1)
    {
        if(t!=0) p2->next=p1;
        p2=p1;
        p1=(SeqList *)malloc(sizeof(SeqList));
        scanf("%d",&p1->num);
        t++;
    }
    p2->next=p1;
    p2=p1;
    p2->next=NULL;
    return head;
}
SeqList *Concatenate(SeqList *p1,SeqList *p2)//连接两链表
{
    SeqList *head;
    if(p1!=NULL)
    {
    head=p1;
    while(p1->next!=NULL)
        p1=p1->next;
    p1->next=p2;
    //free(p2);
    }
    else head=p2;
    return head;
}
int main()
{
    int n,m;
    SeqList *p,*List1,*List2,*NewHead;
    scanf("%d",&n);
    List1=Insert(n);
    scanf("%d",&m);
    List2=Insert(m);
    NewHead=Concatenate(List1,List2);
    p=NewHead;
    while(p->next!=NULL)
    {
        printf("%d ",p->num);
        p=p->next;
    }
    printf("%d\n",p->num);
    return 0;
}

 

 

 

posted on 2012-05-19 12:56  即为将军  阅读(395)  评论(0)    收藏  举报

导航