#include<iostream>
using namespace std;
struct LNode {
int data;
LNode *next;
};
typedef LNode LNode;
typedef LNode *LinkList;
//初始化单链表
void InitList(LinkList &L) {
L = new LNode;
L->next = NULL;
}
//尾插法建立单链表
LinkList TailInsert_List(LinkList &L) {
LNode *r = L;//r为尾指针,尾指针next域开始是NULL
int e;
cout << "请输入数据(输入0结束):" << endl;
cin >> e;
while (e!=0) {
LNode *s = new LNode;//创建新节点
s->next = r->next;//将尾指针next域的东西赋值给新节点的next域
s->data = e;
r->next = s;//新节点的前一个节点(也就是之前的尾指针)的next指向新节点
r = s;//将r移到链表尾,r 继续成为尾结点
cin >> e;
}
r->next = NULL;//最后将尾指针的next置空
return L;//返回单链表
}
void Print_List(LinkList &L) {
LNode *p;
p = L->next;
while (p != NULL) {
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
void Reverse_List(LinkList &L) {
LNode *tail = NULL;
LNode *next;
LNode *curr = L->next;
if (L->next == NULL) return;
if (L->next->next == NULL) return;
while (curr != NULL) {
next = curr->next;
curr->next = tail;
tail = curr;
curr = next;
}
L->next= tail;
}
int main() {
LNode *L;
InitList(L);
TailInsert_List(L);
Print_List(L);
Reverse_List(L);
Print_List(L);
return 0;
}
带头结点的单链表的反转
最新推荐文章于 2022-04-26 11:50:48 发布