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


过了个新年,加上拖拖拖。距离上一篇 数据结构居然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;
}
运行结果:




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值