#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) { //输出链表中的数据
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(Node *&l) { //采用头插法
Node *p = NULL, *r = NULL; //对于空间复杂度为O(1),切记防止断链
p = l->next;
l->next = NULL; //新建只有头结点的链表
while (p != NULL) {
r = p->next; //保存后继指针
p->next = l->next;
l->next = p;
p = r;
}
}
int main() {
Node *l = new Node; //新建结点,并且创建指针
Create(l);
Print(l);
Inverse(l);
Print(l);
Delete(l); //释放内存
system("pause");
return 0;
}
/*
12 43 56 67 34 32 12 65 -1
*/
C++单链表逆置
最新推荐文章于 2021-11-23 12:54:41 发布