C++带头结点单链表逆序输出

#include<iostream>
#define ElemType int
using namespace std;

typedef struct Node {
	ElemType data;
	struct Node *next;
};

void Create(Node *&l) {  //尾插法
	int x;
	l->next = NULL; //头结点
	Node *s,*r = l;  //r为表尾指针
	cin >> x;
	while (x != -1) {
		s = new Node;
		s->data = x;
		r->next = s;
		r = s;
		cin >> x;
	}
	r->next = NULL;
}

void Print(Node *&l) { //输出链表中的数据
	cout << "正常输出:";
	Node *p = l->next;
	while (p != NULL) {
		cout << p->data << " ";
		p = p->next;
	}
	cout << endl;
}

void Delete(Node *&l) { //单链表的删除操作
	Node *p = l;
	Node *q = l->next;  //保存后继指针,防止断链

	while (p!= NULL ) {
		delete p;
		p = q;
		if (q != NULL) {
			q = q->next;
		}
	}
}

void Inverse_set_output(Node *&l) { //采用递归的方式
	if (l->next != NULL) {
		Inverse_set_output(l->next);
	}
	cout << l->data << " ";
}
int main() {
	Node *l = new Node; //新建结点,并且创建指针
	Create(l);
	Print(l);
	cout << "逆置输出:";
	Inverse_set_output(l->next);
	Delete(l);  //释放内存
	system("pause");
	return 0;
}

/*
12 43 56 67 34 32 12 65 -1
*/

猜你喜欢

转载自blog.csdn.net/coolsunxu/article/details/80139162