单链表(链式)c/c++实现

  单链表是一种简单易于理解的数据结构,从实现上来讲有顺序和链式两种。顺序实现主要依赖如数组这样的内存空间连续的结构实现,优点是存取快,可以按照下标随即存取,缺点是必须要占用一块提前指定的连续空间,很可能会造成空间浪费。

  而链式很好的解决了这种浪费现象,代价是不能随机存取数据,性能上会低一些。本文主要给出链式单链表的c/c++实现,如有错误,还望指正。

  代码用cpp格式,g++ -std=c++11编译,本文单链表均含有头结点,这句话表明此单链表的第一个节点是一个不含数据的节点,

仅作表示头的作用。

尾插法:

 1 #include<iostream>
 2 //#include<cstdlib>
 3 using namespace std;
 4 
 5 typedef struct node{
 6     int data;
 7     struct node* next;
 8 }node;
 9 
10 /*
11  *尾插法建立单链表
12  *参数:保存单链表节点数据的文本文件路径(数据之间用空格隔开)
13  *        如data.txt:1 2 3 4 5 6 ...
14    返回:头结点的指针 
15  */
16 node* tail_insert(const char* path){  //path为要打开的文件路径
17     freopen(path,"r",stdin);  //r表示以读方式打开,stdin默认
18     int temp;  
19     node* start=(node*)malloc(sizeof(node));  
20     start->next=nullptr;  //如不支持c++11,请将nullptr全部替换为NULL
21     while(cin>>temp){
22         node* new_node=(node*)malloc(sizeof(node));  //声明新节点并分配空间
23         new_node->data=temp;
24         new_node->next=nullptr;
25         node* tail=start;
26         while(tail->next){  //遍历找到链表的尾节点
27             tail=tail->next;
28         }
29         tail->next=new_node;  //将尾节点接到链表的末尾
30     }
31     fclose(stdin);  //不要忘记关闭输入流
32     return start;  //返回指向头结点的指针
33 }    

头插法:

 1 node* head_insert(const char* path){
 2     freopen(path,"r",stdin);
 3     int temp;
 4     node* start=(node*)malloc(sizeof(node));
 5     start->next=nullptr;
 6     while(cin>>temp){
 7         node* new_node=(node*)malloc(sizeof(node));
 8         new_node->data=temp;
 9         if(start->next)
10             new_node->next=start->next;
11         start->next=new_node;
12     }
13     fclose(stdin);
14     return start;
15 }

遍历打印:

1 void prt(node* start){
2     while(start->next){
3         start=start->next;
4         cout<<start->data;
5     }
6 }

逆序重置单链表:

思路:将头结点后的链表设为一个无头单链表,以头插法将其节点接到头结点的后面,这样就完成了一次逆序。概括来说就是头插法重插。

 1 void reverse(node* start){
 2     node *p=start->next,*q=nullptr;
 3     start->next=nullptr;
 4     while(p){
 5         q=p->next;
 6         p->next=start->next;
 7         start->next=p;
 8         p=q;
 9     }
10 }

猜你喜欢

转载自www.cnblogs.com/kiritozhj/p/10309247.html
今日推荐