#6015. 循环双链表插入值

循环双链表插入值

题目描述

已知循环双链表的节点定义如下:

struct Node {
	int val;
	Node *nxt, *pre;
}; 
Node *head; // 头节点
int tot; // 统计节点数量

你的任务是实现 insertVal 函数:

  • 传入一个节点 p 和一个值 v
  • 在节点 p 后面插入一个数据域为 v 的新节点。

测试程序

#include <bits/stdc++.h>
using namespace std;
struct Node {
	int val;
	Node *nxt, *pre;
}; 
Node *head;
int tot;
// 请在此处实现 insertVal 函数  
// ... 
int main() {
	// 初始化头节点 
	head = new Node;
	head->nxt = head;
	head->pre = head;
	int v1, v2, v3;
	cin >> v1 >> v2 >> v3;
	insertVal(head, v1);	// 在头节点后插入值 v1 
	insertVal(head, v2);	// 在头节点后插入值 v2
	insertVal(head, v3);	// 在头节点后插入值 v3
	// 正序遍历链表 
	Node *t = head->nxt;
	for (int i = 1; i <= 3; i++) {
		cout << t->val << " ";
		t = t->nxt; 
	}
	cout << endl;
	// 倒序遍历链表 
	t = head->pre;
	for (int i = 1; i <= 3; i++) {
		cout << t->val << " ";
		t = t->pre; 
	} 
	t = head->nxt; 
	for (int i = 1; i <= 3; i++) {
		Node *q = t->nxt;
		delete t;
		t = q;
	}
	delete head;
	return 0;
}

题型说明

解题时可以把题目提供的程序复制到编译器中,编写对应所需的函数,测试通过后只需要提交所需的函数,如果提交完整程序反而会 WA

格式要求

输入格式

输入 33int 类型的整数,代表链表 33 个节点的数据域。

输出格式

输出 22 行,每行 33 个空格隔开的数字,分别代表正序遍历和倒序遍历链表的结果。

样例

1 2 3
3 2 1
1 2 3

提示

可以试着使用 insertNode 函数简化代码。