include<stdio.h>
#include<stdlib.h>
struct iNode{
int data;
struct iNode *next;
};
struct iNode *create()
{
struct iNode *hp =NULL;//head
struct iNode *tp =NULL;//tail
struct iNode *cp =NULL;//current
int data;
while(1)
{
scanf("%d",&data);
if(data <= 0)break;
cp =(struct iNode*)malloc(sizeof(struct iNode));
if(cp ==NULL)
{
printf("OVER FLOW");
break;
}
cp->data = data;
cp->next =NULL;
if(hp ==NULL)
{
hp = tp = cp;
}else{
tp->next = cp;
tp = cp;
}
}
printf("Create Success!/n");
return hp;
}
void head_insert(struct iNode *head,int position,int val)
{
struct iNode *p = head;
struct iNode *node =NULL;
int i = 0;
while(p &&++i < position -1)
{
p = p -> next;
//++i;
}
node =(struct iNode *)malloc(sizeof(struct iNode));
node->data = val;
node->next = p->next;
p->next = node;
}
void tail_insert(struct iNode *head,int position,int val)
{
struct iNode *p = head;
struct iNode *node =NULL;
int i = 0;
while(p &&++i < position)
{
p = p->next;
}
node =(struct iNode *)malloc(sizeof(struct iNode));
node->data = val;
node->next = p->next;
p->next = node;
}
void del_node(struct iNode *head,int position,int val)
{
struct iNode *p = head;
struct iNode *d =NULL;
int i = 0;
while(p &&++i < position -1){
p = p->next;
}
d = p->next;
p->next = d->next;
val = d->data;
free(d);
}
void printl(struct iNode *head)
{
struct iNode *p = head;
if(p !=NULL)
{
do{
printf("%d ",p->data);
p = p->next;
}while(p !=NULL);
}else{
printf("List ERROR/n");
}
printf("/n");
}
int main()
{
struct iNode *list= create();
int val = 0;
printf("List:/n");
printl(list);
printf("/n/nInserted 1:/n");
head_insert(list,5,34);
printl(list);
printf("/n/nDeleted:/n");
del_node(list,5,val);
printl(list);
printf("Element: %d/n",val);
printf("/n/nInserted 2:/n");
tail_insert(list,5,32);
printl(list);
return 0;
}
顺序链表
最新推荐文章于 2024-10-16 16:57:11 发布