您的位置:首页 > 编程语言 > C语言/C++

链表的创建、测长、排序、插入、逆序的实现(C语言)

2013-11-21 13:46 519 查看
#include <stdio.h>
#define END_elem 0

struct node
{
int date;
struct node * next;
};

//链表创建
node * creat()
{
int x;
    node *head,*last,*p;
    head=new node();
    last=head;
scanf("%d",&x);
while(x!=END_elem)
{
        p=new node();
        p->date=x;
        last->next=p;
        last=p;
scanf("%d",&x);
}
    head=head->next;
    last->next=NULL;
return head;
}

//单链表测长
int lenght(node *head)
{
int n=0;
    node *p=head;
while(p!=NULL)
{
        p=p->next;
        n++;
}
return n;
}

//链表排序
node *sort(node *head,int n)
{
int temp;
    node *p;
if(head==NULL||head->next==NULL)
return head;
for(int i=0;i<n-1;i++)
{
        p=head;
for(int j=0;j<n-1-i;j++)
{
if(p->date>p->next->date)
{
                temp=p->date;
                p->date=p->next->date;
                p->next->date=temp;
}
            p=p->next;
}
}
return head;
}

//链表插入
node * insert(node *head,int num)
{
    node *p,*q,*t;
    p=head;
    t=new node();
    t->date=num;
while(num>p->date&&p->next!=NULL)
{
        q=p;
        p=p->next;
}
if(num<=p->date)
{
if(p==head)
{
            t->next=p;
            head=t;
}
else
{
            t->next=p;
            q->next=t;
}
}
else//把插入点定在表尾
{
        p->next=t;
        t->next=NULL;
}
return head;
}

//链表输出
void print(node *head)
{
struct node *p=head;
while(p!=NULL)
{
printf("%d\n",p->date);
        p=p->next;
}
}

//链表删除
node *del(node *head,int num)
{
    node *p,*q;
    p=head;
while(num!=p->date&&p->next!=NULL)
{
        q=p;
        p=p->next;
}
if(p->date==num)
{
if(p==head)
{
            head=p->next;
            delete p;
}
else
{
            q->next=p->next;
            delete p;
}
}
else
printf("Didn't Fond The Num!");
return head;
}

//链表逆序
node *reverse(node *head)
{
    node *p1,*p2,*p3;
    p1=head;
    p2=head->next;
while(p2)
{
        p3=p2->next;
        p2->next=p1;
        p1=p2;
        p2=p3;
}
    head->next=NULL;
    head=p1;
return head;
}

void main()
{
struct node *head;
int n,m;

printf("链表创建,输入数字:\n");
    head=creat();
    print(head);

    n=lenght(head);
printf("链表的长度为 %d\n",n);

printf("链表排序:\n");
    head=sort(head,n);
    print(head);

printf("输入要插入链表的数:\n");
scanf("%d",&m);
printf("插入后的链表:\n");
    head=insert(head,m);
    print(head);

printf("链表逆序:\n");
    head=reverse(head);
    print(head);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐