#include <stdio.h>
typedef struct element{
int value;
struct node *next;
}node;
node *head,*p1,*p2;
node *creatlist();
void print(node *head);
node *insert(node *head,int index,int v);
node *removelement(node *head,int index);
node *destroy(node *head);
int main(int argc, char *argv[])
{
int num,v;
head=creatlist();
printf("\n原始链表元素是:\n");
print(head);
printf("\n请告诉我你要在哪个位置插入节点:");
scanf("%d",&num);
printf("\n节点数值是:");
scanf("%d",&v);
head=insert(head,num,v);
print(head);
printf("\n请告诉我你要删除哪个节点:");
scanf("%d",&num);
head=removelement(head,num);
print(head);
head=destroy(head);
return 0;
}
node *creatlist(){
int n=0;
head=NULL;
if(n==0){
p1=p2=(node *)malloc(sizeof(node));
head=p1;
p1->value=100;
p1->next=NULL;
n++;
}
for(n=1;n<10;n++){
p2=(node *)malloc(sizeof(node));
p1->next=p2;
p2->value=10*n;
p2->next=NULL;
p1=p2;
}
return head;
}
void print(node *head){
node *list;
list=head;
while(list!=NULL){
printf("%d\t",list->value);
list=(list->next);
}
}
node *insert(node *head,int index,int v){
int i=0;
node *list;
node *old;
node *newnode;
list=head;
while(1==1){
if(i==index){
old=(list->next);
newnode=(node *)malloc(sizeof(node));
list->next=newnode;
newnode->next=old;
newnode->value=v;
break;
}else{
list=(list->next);
i++;
}
}
return head;
}
node *removelement(node *head,int index){
node *list;
node *newnext,*temp;
int j=0;
list=head;
while(1==1){
if(j==(index-1)){
temp=(list->next);
newnext=temp->next;
list->next=newnext;
break;
}else{
list=(list->next);
j++;
}
}
return head;
}
node *destroy(node *head){
node *list;
list=head;
while(list!=NULL){
printf("%d\t",list->value);
list=(list->next);
free(head);
}
}
注:本程序未考虑索引越界的问题
数据结构之链表
最新推荐文章于 2019-11-01 22:04:43 发布