数据结构与算法:链表(源码)!

今天抽了点时间,复习了一下链表,总结了建立,删除,插入,查找的操作方法。

源码如下:

 

复制代码
#include < iostream >
using   namespace  std;

typedef 
struct  LNode 

int  data; 
struct  LNode  * next; 
}LNode,
* Llist; 

// 方法声明
LNode  * creat_head(); // 创建一个空表 
void  creat_list(LNode  * , int ); // 创建一个长度为n的线性链表 
void  insert_list(LNode  * , int , int  ); // 插入一个元素 
int  delete_list(LNode  * , int ); // 删除一个元素 

// 创建一个空链表 
LNode  * creat_head()

LNode 
* p; 

p
= (Llist)malloc( sizeof (LNode)); 

p
-> next = NULL; 

return (p); 


// 创建一个长度为n的线性链表 
void  creat_list(LNode  * head, int  n) 

LNode 
* p, * q;
int  i;
p
= head; 
for (i = 1 ;i <= n;i ++

q
= (Llist)malloc( sizeof (LNode)); 
cout
<< " data: " ;
cin
>> q -> data; 
q
-> next = NULL; 
p
-> next = q; 
= q; 



// 插入一个元素 
void  insert_list(LNode  * head, int  x, int  i ) 

int  j = 0 ;
LNode 
* p, * s; 
p
= head; 
while ((p != NULL) && (j < i - 1 )) 

p
= p -> next; 
j
++

if (p == NULL) 
exit(
0 ); 
s
= (Llist)malloc( sizeof (LNode)); 
s
-> data = x; 
s
-> next = p -> next; 
p
-> next = s; 
}

// 删除一个元素 
int  delete_list(LNode  * head, int  i) 

LNode 
* p, * q; 
int  j = 0
int  x; 
p
= head; 
while ((p != NULL) && (j < i - 1 )) 

p
= p -> next; 
j
++

if (p == NULL) 
exit(
0 ); 
q
= p -> next; 
p
-> next = q -> next; 
x
= q -> data; 
delete(q); 
return (x); 

// 输出
void  Print(LNode  * head,LNode  * p){
     
for (p = head -> next;p != NULL;) 
     { 
     cout
<< p -> data << endl; 
     p
= p -> next;
     } 
     } 
// 按序号查找
int  Find(LNode  * head,LNode  * p, int  i){
    
int  j = 0 ;
    
int  k;
    
for (p = head -> next;p != NULL;){
    j
++ ;
    
if (i == j)
    k
= p -> data;
    p
= p -> next;
    }
    
return  k;
}
// 主函数 
int  main() 

LNode 
* head, * p; 
int  find; 
int  n; 
int  x,i; 
int  b; 
int  clrscr(); 
head
= creat_head(); 
cout
<< " 请输入链表长: " << endl; 
cout
<< " n= " ;
cin
>> n; 
cout
<< " 请输入数值: " << endl; 
creat_list(head,n);
cout
<< " 您输入的链表为: " << endl; 
Print(head,p);
cout
<< " \n请输入您要插入的数:\n "
cout
<< " x= " ;
cin
>> x; 
cout
<< " \n请输入您要插入的位置:\n "
cout
<< " i= " ;
cin
>> i; 
insert_list(head,x,i); 
cout
<< " 您输入的链表为: " << endl; 
Print(head,p);
cout
<< " \n请输入您要删除的位置:\n "
cout
<< " i= " ;
cin
>> i; 
b
= delete_list(head,i);
cout
<< " 删除后的链表为: " << endl; 
Print(head,p);
cout
<< " 请输入您要查找的位置: " << endl;
cin
>> find;
cout
<< Find(head,p,find) << endl;
cout
<< " 请输入您要查找的位置: " << endl;
cin
>> find;
cout
<< Find(head,p,find) << endl;
cout
<< " 请输入您要查找的位置: " << endl;
cin
>> find;
cout
<< Find(head,p,find) << endl;
return   0 ;

复制代码

 本文转自施杨博客园博客,原文链接:http://www.cnblogs.com/shiyangxt/archive/2008/12/01/1345303.html,如需转载请自行联系原作者

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值