数据结构之链表

#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);
	}
 		
 		
 	}
注:本程序未考虑索引越界的问题

                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值