您的位置:首页 > 理论基础 > 数据结构算法

算法进行时--单链表(一)头尾插法

2017-02-19 22:43 183 查看
过了个新年,加上拖拖拖。距离上一篇 数据结构居然5个月了,哎



链表应该是当时学数据结构用得最多的了,面试的话考它的也多,它用的指针的时候也多,but 数据结构学了一年多了,差不多的都忘记了,打算开始复习一遍,毕竟靠它买面膜,哈哈。

链表第一题first:

链表中首先开始学的最多就是用头插法和尾插法:

头插法:

每次都从头开始插入结点。



/*
Instruction:Head insertion
author:huangpingyi
date:2017/02/19
*/

#include <iostream>
using namespace std;

struct LNode
{
int data;
LNode *next;
};

LNode* CreateListH(LNode *L, int x, int array[])
{
L->next = NULL;
LNode *s;//插入的结点
int i = 0;
while (i < x)
{
s = new LNode;
s->data = array[i];
s->next = L->next;
L->next = s;
i++;
}
return L;
}
void Print(LNode *L)
{
L = L->next;//第一个是头结点
while (L != NULL)
{
cout << L->data << endl;
L = L->next;
}
}
int main(){
int x, array[10];
cout << "请输入插入个数:" << endl;
cin >> x;
cout << "输入需要插入的数据:" << endl;
for (int i = 0; i < x; i++)
{
cin >> array[i];
}
LNode* L = new LNode;
CreateListH(L, x, array);
cout << "用头插法的结果:" << endl;
Print(L);
system("pause");
return 0;
}


运行结果:



尾插法:

正如它的它的名字一样,每次都是从尾部插和头插法刚好相反



/*
Instruction:Tail insertion
author:huangpingyi
date:2017/02/19
*/

#include <iostream>
using namespace std;

struct LNode
{
int data;
LNode *next;
};

LNode* CreateListT(LNode *L, int x, int array[])
{
L->next = NULL;
LNode *q = L;
LNode *s;//插入的结点
int i = 0;
while (i < x)
{
s = new LNode;
s->data = array[i];
//以下三步是尾插法和头插法的区别
L->next = s;
s->next = NULL;
L = s;
i++;
}
return q;
}
void Print(LNode *L)
{
L = L->next;//第一个是头结点
while (L != NULL)
{
cout << L->data << endl;
L = L->next;
}
}
int main(){
int x, array[10];
cout << "请输入插入个数:" << endl;
cin >> x;
cout << "输入需要插入的数据:" << endl;
for (int i = 0; i < x; i++)
{
cin >> array[i];
}
LNode* L = new LNode;
CreateListH(L, x, array);
cout << "用尾插法的结果:" << endl;
Print(L);
system("pause");
return 0;
}
运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息