c语言数据结构(链表的插入和删除)

链表的插入和删除代码
2025-05-21 04:52:30
推荐回答(1个)
回答(1):

下面是我的源代码,你看看,应该可以帮上你的 :-)

/*
* singleLinkedList.cc
*
* Created on: 2010-6-1
* Author: LiuFeng
*
*/

#include
#include
#include

typedef struct node {
int data;
node* next;
} node;

node*
search_node(node* head, int pos){
node*p=head->next;
if(pos<0){
printf("incorrect position to search node:\n");
return NULL;
}
if(pos==0){
return head;
}
if(p==NULL){
printf("List is empty\n");
return NULL;
}

while(--pos){
if((p=p->next)==NULL){
printf("incorrect postion to search node!\n");
break;
}
}
return p;
}

node*
insert_node(node* head, int pos, int data){
node* item=NULL;
node* p;

item = (node*)malloc(sizeof(node));
item->data=data;
if(pos==0){
head->next=item;
return head;
}
p=search_node(head,pos-1);
if(p!=NULL){
item->next=p->next;
p->next=item;
}
return head;
}

node*
delete_node(node*head, int pos){
node* item=NULL;
node* p = head->next;
if(p==NULL){
printf("link is empty\n");
return NULL;
}
p=search_node(head, pos);
if(p!=NULL&& p->next!=NULL){
item=p->next;
p->next=item->next;
delete item;
}
return head;
}

int length(node * head){
int len=0;
node *p;
p=head->next;
while(p!=NULL){
++len;
p=p->next;
}
return len;
}