#include <stdio.h>
#include <malloc.h>
typedef struct Node
{
int data;
struct Node *next;
}Node,*linklist;
linklist create(int n)
{
int i;
linklist head,p;
for(i=0;i<n;++i)
{
p=(Node*)malloc(sizeof(Node));
printf("please input number to data %d!",i);
scanf("%d",&p->data);
p->next=head;
head=p;
}
return head;
}
void print(linklist head)
{
linklist p;
p=head;
while(p->next!=NULL)
{
printf("%4d",p->data);
p=p->next;
}
printf("\n");
}
linklist insert(linklist head,int elem,int index)
{
linklist p,q;
int i=0;
p=head;
q=(Node*)malloc(sizeof(Node));
q->data=elem;
while(p->next!=NULL&&i<index)
{
p=p->next;
i++;
}
if(p->next==NULL)
{
printf("linklist is short!");
}
else
{
q->next=p->next->next;
p->next=q;
}
return head;
}
linklist delete(linklist head,int index)
{
int i=0;
linklist p,q;
p=head;
q=head->next;
while(i<index&&p->next!=NULL)
{
p=p->next;
i++;
}
if(q->next==NULL)
{
printf("linklist is short!");
}
else
{
q=p->next;
p->next=q->next;
free(q);
}
return head;
}
int main()
{
int n;
linklist head;
printf("please input number to n!");
scanf("%d",&n);
head=create(n);
print(head);
insert(head,23,3);
print(head);
delete(head,5);
print(head);
return 0;
}
数据结构—单向链表
最新推荐文章于 2024-08-10 18:31:58 发布