c ++ 链表

#pragma once
#include <iostream>
using namespace std;
struct Node {
	int val;
	Node* next;
	Node(int val, Node* next) :val(val), next(next) {};
	Node(int val) :val(val), next(nullptr) {};
};

class LinkedList {
public:
	Node* create() {
		Node* head = nullptr;
		Node* tail = nullptr;
		int k;
		cout << "输入-1退出创建程序:";
		cin >> k;
		while (k != -1) {
			Node* newnode = new Node(k);
			if (head == nullptr) {
				head = newnode;
				tail = newnode;
			}
			else {
				tail->next = newnode;
				tail = newnode;
			}
			cout << "输入-1退出创建程序:";
			cin >> k;
		}
		return head;
	}
	void show(Node* head) {
		Node* cur = head;
		while (cur != nullptr) {
			cout << cur->val << "->";
			cur = cur->next;
		}
	}
	int len(Node* head) {
		Node* cur = head;
		int size = 0;
		while (cur != nullptr) {
			size++;
			cur = cur->next;
		}
		return size;
	}
	Node* deleteAtIndex(Node* head,int idx) {
		Node* cur = head;
		if (idx == 0) { return head->next; }
		else {
			for (int i = 0; i < idx - 1; ++i) {
				cur = cur->next;
			}
			Node* temp = cur->next;
			cur->next = cur->next->next;
			delete temp;
		}
		return head;
	}
	Node* deleteAtval(Node* head, int val) {
		Node* cur = head;
		if (head->val == val) { head = head->next; }
		while (cur->next != nullptr) {
			if (cur->next->val == val) {
				Node* temp = cur->next;
				cur->next = cur->next->next;
				delete temp;
			}
			else { cur = cur->next; }
		}
		return head;
	}
	Node* addAtIndex(Node* head, int val, int idx) {
		Node* newnode = new Node(val);
		Node* cur = head;
		if (idx == 0) {
			newnode->next = cur->next;
			cur->next = newnode;
			return head;
		}
		else {
			while (idx--) { cur = cur->next; }
		}
		newnode->next = cur->next;
		cur->next = newnode;
		return head;
	}
};

链表不同于数组,数组中的数据是连接的,较为密集的,内存地址是连续的,比如我构建一个整数类型的数组,数组中的每个数都是整数,占4个字节,也就是32位,在查询内存地址时就会发现相邻的数字的内存地址只相差4,而链表则是通过链条的方式,将散落在各个地方的数据连接起来,较为灵活,同时方便修改

这个是写了个头文件,下面是我调用的主程序

#include <iostream>
#include"LinkedList.h";
using namespace std;
int main() {
	LinkedList l;
	Node* head = l.create();
	head = l.addAtIndex(head, 1000, 0);
	head = l.addAtIndex(head,1000, 1);
	l.show(head);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值