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

链表的插入和删除代码... 链表的插入和删除代码 展开
 我来答
sohu2000000

2010-06-04 · TA获得超过237个赞
知道小有建树答主
回答量:126
采纳率:0%
帮助的人:120万
展开全部
下面是我的源代码,你看看,应该可以帮上你的 :-)

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

#include <iostream>
#include <cstdlib>
#include <cstdio>

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;
}
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式