链表的创建及输入输出 验证q= p->next q->next = p->next的情况

链表的创建及输入输出

#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* next) : val(x), next(next) {};
};

int main() {
	vector<int> a{2,4,3};

	auto dummy = new ListNode();
	auto tail = dummy;

	for (auto x : a) {
		auto node = new ListNode(x);
		tail = tail->next = node;
	}

	auto head = dummy->next;

	for (auto p = head;p;p = p->next) {
		cout << p->val << endl;

	}
	return 0;
}


验证q= p->next; q->next = p->next的情况

#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* next) : val(x), next(next) {};
};

int main() {
	vector<int> a{ 1, 2, 3, 4, 5};

	auto dummy = new ListNode();
	auto tail = dummy;

	for (auto x : a) {
		auto node = new ListNode(x);
		tail = tail->next = node;
	}

	auto head = dummy->next;
	auto t = head;

	for (auto p = head; p; p = p->next) {
		cout << p->val << endl;
		cout << p->next << endl;
	}


	t = head->next;
	cout << t->val << ' ' << t->next << endl;
	t->next = head->next;
	cout << t->val << ' '<< t->next << endl;


	return 0;
}



你可能感兴趣的:(数据结构与算法,链表,单链表)