链表的创建,添加,排序,输出的简单例子

#import <Foundation/Foundation.h>
#include <stdio.h>

typedef struct node
{
int data;
struct node *next;
}List;//定义一个int类型的结构体,名字为List

List *insert(List *p,List *q);//插入函数,,p新元素插入位置,q 新元素中的数据域内容
List *create(void);//创建函数。
void print(List *head);//打印函数。

List *insert(List *p,List *q)//插入函数
{
List *k,*t;
t=p;
while(t!=NULL)
{
        if(t->data>q->data)break;
        k=t;
        t=t->next;
}
q->next=k->next;
k->next=q;
return p;//p保持是最小的数。p 其实是整个链表。
}

List *create(void)
{
int i=0;
List *head,*p,*q;//p 为链表的元素,q为链表的尾。
head=(List *)malloc(sizeof(List));
q=p=(List *)malloc(sizeof(List));
scanf("%d",&q->data);
q->next=NULL;
while(q->data!=0)//判断尾是否为0;
{
        i++;
        if(i==1)
            head->next=p;
        else
        {
            if(q->data<p->data)//小于的时候使用头插法
            {
                q->next=p;
                head->next=q;
                p=q;
            }
            else p=insert(p,q);//大于的时候使用插入函数
        }
        q=(List *)malloc(sizeof(List));//每次添加一个尾,就新开辟一个新尾的空间。
        scanf("%d",&q->data);
}
return head;
}


void print(List *head)
{
List *p;
p=head->next;
while(p!=NULL)
{
        printf("%d ",p->data);//P对象的元素值。
        p=p->next;//把元素的值赋为下个元素的值。
}
}


int main (int argc, const char * argv[])
{

    @autoreleasepool {
       
        int x;
        List *head,*p;
        printf("请向链表中输入数值,按0结束:\n");
        head=create();
        printf("得到的链表为:\n") ;
        print(head);
        printf("\n");
        printf("请输入一个数值,插入到链表中:\n");
        scanf("%d",&x);
        p=(List *)malloc(sizeof(List));
        p->data=x;
        head=insert(head,p);
        printf("插入数值后的链表为:\n");
        print(head);
           
    }
    return 0;
}

猜你喜欢

转载自zhangmingwei.iteye.com/blog/1742899