1个回答
展开全部
下面是我的源代码,你看看,应该可以帮上你的 :-)
/*
* 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;
}
/*
* 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;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询