链表操作—头插法尾插法

单链表的插入操作,包括头插和尾插,两种的时间复杂度都为O(n)。

/*
	单链表插入操作(头插+尾插)
*/
#include<iostream>
#include<malloc.h>
using namespace std;
//定义结点数据类型
typedef int Elemtype;

//结点定义
typedef struct LNode {
    
    
	Elemtype data;
	LNode* next;
}LNode, * Linklist;

//单链表的初始化
Linklist initList() {
    
    
	Linklist L;
	L = (Linklist)malloc(sizeof(LNode));
	L->next = NULL;
	return L;
}
//头插法
void headInsert(Linklist& L) {
    
    
	Linklist p;
	p = (Linklist)malloc(sizeof(LNode));
	cout << "输入链表的数据,-1表示结束" << endl;
	cin >> p->data;
	while (p -> data != -1) {
    
    
		p->next = L->next;
		L->next = p;
		p = (Linklist)malloc(sizeof(LNode));
		cin >> p->data;
	}
}

//尾插法
void tailInsert(Linklist &L) {
    
    
	Linklist p,end;//end表示尾指针
	end = L;
	p = (Linklist)malloc(sizeof(LNode));
	cout << "输入链表的数据,-1表示结束" << endl;
	cin >> p->data;
	while (p->data != -1) {
    
    
		p->next = end->next;
		end->next = p;
		end = p;//尾指针向后移
		p = (Linklist)malloc(sizeof(LNode));//重新分配内存
		cin >> p->data;//继续增加结点
	}
	end->next = NULL;
}

//打印链表
void printList(Linklist& L) {
    
    
	Linklist p;
	p = L->next;
	while (p) {
    
    
		cout << p->data << " ";
		p = p->next;
	}
	cout << endl;
}
int main()
{
    
    
	Linklist L = initList();
	cout << "选择创建单链表方式:1.头插法  2.尾插法" << endl;
	int s;
	cin >> s;
	if (s == 1) {
    
    
		headInsert(L);
		cout << "头插法创建出的链表为:";
		printList(L);
	}
	else if (s == 2) {
    
    
		tailInsert(L);
		cout << "尾插法创建出的链表为:";
		printList(L);
	}
	else {
    
    
		cout << "出错" << endl;
	}
	return 0;
}

运行结果
在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Gentle722/article/details/106172974