链表(类封装)C++

#include<iostream>
using namespace std;
class Node {
public:
	int val;
	Node* next;
	Node() :val(0), next(nullptr) {}
	Node(int x) :val(x), next(nullptr) {}
	void PrintNode();
};
void Node::PrintNode() {
	cout <<val<<endl;
}
class ListNode {
private:
	Node* head;
public:
	ListNode();
	void AddNodePre(Node* node);
	void AddNodePost(Node* node);
	void CreateList(int n);
	void PrintList();
	void DeleteNode(int x);
	int GetSize();
	void ModifyNode(int pos, int val);
	~ListNode();
};
ListNode::ListNode() {
	head = new Node();
}
void ListNode::AddNodePre(Node *node) {
	Node* temp = new Node(*node);
	//头插法
	temp->next = head->next;
	head->next = temp;
}
void ListNode::AddNodePost(Node* node) {
	Node* temp = new Node(*node);
	Node* t = head;
	while (t->next) {
		t = t->next;
	}
	t->next = temp;
}
void ListNode::PrintList() {
	Node* temp = head->next;
	while (temp) {
		temp->PrintNode();
		temp = temp->next;
	}
}
void ListNode::CreateList(int n) {
	Node* t = head;
	for (int i = 0; i < n; i++) {
		Node* temp = new Node(i);
		t->next = temp;
		t = t->next;
	}
	return;
}
void ListNode::DeleteNode(int x) {
	//x表示第几个节点 head不算
	int i = 1;
	Node* node = head->next;
	Node* t = head;
	while (node) {
		if (i == x) {
			t->next = node->next;
			delete node;
			break;
		}
		t = t->next;
		node = node->next;
		i++; 
	}
}
int ListNode::GetSize() {
	Node* temp = head->next;
	int i = 0;
	while (temp) {
		i++;
		temp = temp->next;
	}
	return i;
}
void ListNode::ModifyNode(int pos, int val) {
	Node* temp = head->next;
	int i = 0;
	while (temp) {
		i++;
		if (i == pos) {
			temp->val = val;
			break;
		}
		temp = temp->next;
	}
}
ListNode::~ListNode() {
	Node* temp = head;
	Node* t;
	while (temp) {
		t = temp->next;
		delete temp;
		temp = t;
	}
}
int main() {

	ListNode test;
	cout << "初始:" << endl;
	Node node1(25);
	Node node2(26);
	Node node3(27);
	Node node4(28);
	test.AddNodePre(&node1);
	test.AddNodePre(&node2);
	test.AddNodePost(&node3);
	test.AddNodePost(&node4);
	test.PrintList();
	 
	ListNode test1;
	test1.CreateList(10);
	cout << "初始" << endl;
	test1.PrintList();
	int len=test1.GetSize();
	cout << "长度:" << len << endl;
	cout << "删除第三个" << endl;
	test1.DeleteNode(3);
	test1.PrintList();
	cout << "第五个位置上改成100" << endl;
	test1.ModifyNode(5, 100);
	test1.PrintList();
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值