栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

链表c++构建与操作

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

链表c++构建与操作

数据结构C++实现:王道考研学习笔记—链表

顺序表:
优点:可随机存取,存储密度高
缺点:要求大片连续空间,改变容量不方便

链表:
优点:不要求大片连续空间,改变容量方便
缺点:不可随机存取,要耗费一定空间存放指针

#include 
#include 
#include 
using namespace std;

//链表节点结构
struct ListNode {
	int val;
	ListNode* next;
	ListNode() : val(0), next(nullptr) {}
	ListNode(int x) : val(x), next(nullptr) {}
	ListNode(int x, ListNode* p) : val(x), next(p) {}
};

// 获取链表中第k个元素
ListNode* get(ListNode* &head, int i) {
	int j = 1;
	ListNode* p = head;
	if (i == 0) {
		return head;
	}
	if (i < 1) {
		return nullptr;
	}
	while (p != nullptr) {
		if (j == i) {
			break;
		}
		j++;
		p = p->next;
	}
	return p;
}

//头插法构建链表
ListNode* BuildHeadListNode(ListNode * head,vector num) {
	for (auto it = num.rbegin(); it != num.rend(); ++it) {
		ListNode* p = new ListNode(*it, head->next);
		head->next = p;
	}
	return head;
}

//尾部插法构建链表
ListNode* BuildTailListNode(ListNode* head, const vector& num) {
	ListNode* pre = head;
	for (auto it = num.begin(); it != num.end(); ++it) {
		ListNode* p = new ListNode(*it,nullptr);
		pre->next = p;
		pre = p;
	}
	return head;
}

//倒数第k个节点
ListNode* getKthFromEnd(ListNode* head, int k) {
	ListNode* fp = head;
	ListNode* sp = head;
	while (fp != nullptr && k--) {
		fp = fp->next;
	}
	while (fp != nullptr) {
		fp = fp->next;
		sp = sp->next;
	}
	return sp;
}

//从头到尾打印链表
void printListNode(ListNode* head) {
	while (head != nullptr) {
		cout << head->val << " ";
		head = head->next;
	}
}


//从尾到头打印链表
void reprintListNode(ListNode* head) {
	if (head == nullptr) {
		return;
	}
	reprintListNode(head->next);
	cout << head->val << " ";
}

//反转链表
ListNode* reverseList(ListNode *head) {
	ListNode* cur = head;
	ListNode* pre = nullptr;
	while (cur != nullptr) {
		ListNode* next = cur->next;
		cur->next = pre;
		pre = cur;
		cur = cur->next;
	}
	return pre;
}
int main() {
	vector v = {1,2,3,4,5};
	ListNode* head = new ListNode();

	head = BuildHeadListNode(head, v);
	//head = BuildTailListNode(head, v);
	head = head->next;

	int i = 1;
	ListNode* p = get(head, i);
	cout << "获取第"<< i<<"个点的元素"<< endl;
	if (p != nullptr) {
		cout << p->val << endl;
	}
	else {
		cout << "-1" << endl;
	}

	cout << "倒数第k个节点:"<< endl;
	cout << getKthFromEnd(head, 1)-> val << endl;
	cout << "从头到尾打印链表" << endl;
	printListNode(head);
	cout << endl;

	cout << "从尾到头打印链表" << endl;
	reprintListNode(head);
	cout << endl;

	//反转链表
	cout << endl;
	reverseList(head);
	printListNode(head);
	cout << endl;

	return 0;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/330394.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号