单向链表C语言实现

//************************************
//本程序演示内容如下:
//1.根据输入创建一个单链表
//2.显示单链表
//3.在单链表的任意位置插入一个节点
//4.在单链表的任意位置删除一个节点
//zping 2012-3-14
//************************************


#include <stdio.h>
#include <malloc.h>


//定义链表结构
typedef struct
{
    int num;
    struct ListNode *next;
} ListNode;


//根据输入创建一个单链表,输入0结束
ListNode *CreatList(int *len)
{
    int temp,n=0;
    ListNode *head;
    ListNode *p1,*p2;
    
    printf("you can exit with 0,please enter a num:\n");
    scanf("%d",&temp);
head=NULL;
    while(temp!=0)
    {
        if(head==NULL) 
{
if((p1=(ListNode *)malloc(sizeof(ListNode)))==NULL)
{
printf("malloc error!\n");
return NULL;
}
head=p1;
p1->num=temp;
n=1;
}
else
{
if((p2=(ListNode *)malloc(sizeof(ListNode)))==NULL)
{
printf("malloc error!\n");
return NULL;
}
p2->num=temp;
p1->next=p2;
p1=p2;
p2->next=NULL;
n++;
}
printf("you can exit with 0,please enter a num:\n");
scanf("%d",&temp);
    }
*len=n;
    printf("This ListTabke lenght is:%d\n",n);
    return head;
}


//显示一个单链表
void ShowList(ListNode *p)
{
    ListNode *temp=p;
    printf("ListTable:");
    while(temp!=NULL)
    {
        printf("%d ",temp->num);
        temp=temp->next;
    }
    printf("\n");
}


//在单链表指定位置插入一个节点,pos取值[1,len+1]
ListNode *InsertList(ListNode *head,int pos,int *len)
{
int i,temp;
    ListNode *p=head,*t,*x;


    if(pos<1 || pos>((*len)+1))
    {
        printf("parameter error!\n");
return NULL;
    }
    printf("please enter a num:\n");
    scanf("%d",&temp);
    if((t=(ListNode *)malloc(sizeof(ListNode)))==NULL)
{
printf("malloc error!\n");
return NULL;
}
t->num=temp;

for(i=2;i<pos;i++)
{
p=p->next;
}


if(pos==1)
{
head=t;
t->next=p;
}
else
{
x=p->next;
p->next=t;
if(pos==((*len)+1))
t->next=NULL;
else
t->next=x;
}
        
    printf("Insert Success.\n");
    (*len)++;
    return head;
}


//删除单链表指定位置一个节点,pos取值[1,len]
ListNode *DeleteList(ListNode *head,int pos,int *len)
{
int i;
    ListNode *p=head,*x;

    if(pos<1 || pos>(*len))
    {
        printf("parameter error!\n");
return NULL;
    }


for(i=2;i<pos;i++)
{
p=p->next;
}

if(pos==1)
{
head=p->next;
free(p);
}
else
{
x=p->next;
p->next=x->next;
free(x);
}


printf("Delete Success.\n");
    (*len)--;
    return head;
}


int main(void)
{
    int len,pos=0;
    ListNode *head;
    if(NULL!=(head=CreatList(&len)))
ShowList(head);


printf("please enter insert position:\n");
scanf("%d",&pos);
    if((head=InsertList(head,pos,&len))!=0)
ShowList(head);


printf("please enter delete position:\n");
scanf("%d",&pos);
if(NULL!=(head=DeleteList(head,pos,&len)))
ShowList(head);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值