Files
Data_Structure/Chapter2/2-5-ReverseLinkList/ReverseLinkList.cpp

82 lines
1.7 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#include<iostream> //cout,cin
using namespace std;
#include "LinkList.h"
//算法2.25 单链表逆置
void ReverseLinkList(LNode<int>*& L)
{
LNode<int>* p, * q; // 1.设置工作指针
p = L->next; // 原链表头结点,作为逆置后表的头结点
L->next = NULL;
while (p) // 2. 依次摘除原链表结点,以头插法插入到逆置链表中
{
q = p; // 2.1 q取当前结点位置
p = p->next; // 2.2 p指向下一个待处理结点
q->next = L->next; // 2.3 将q 插入到头结点之后
L->next = q;
}
}
void dispmenu()
{//显示主菜单
cout << endl;
cout << "1-创建单链表\n";
cout << "2-逆置单链表\n";
cout << "3-显示单链表\n";
cout << "4-退出\n";
}
char pause;
//主函数
int main()
{
int n;
//int e;
LNode<int>* L;
system("cls"); // 执行系统命令cls清屏
int choice;
do
{
dispmenu(); // 显示主菜单
cout << "Enter choice(1~4):";
cin >> choice;
switch (choice)
{
case 1: // 创建单链表
InitList(L);
cout << "输入要创建元素个数:";
cin >> n;
cout << endl;
CreateList_1(L, n);
cout << "创建的单链表为:";
DispList(L);
cout << endl;
break;
case 2: // 逆置单链表
ReverseLinkList(L);
cout << "逆置后的单链表为:";
DispList(L);
cout << endl;
break;
case 3: // 显示表
DispList(L);
cout << endl;
cin.get(pause);
system("pause");
break;
case 4: // 退出
DestroyList(L);
cout << "结束运行" << endl;
break;
default: // 无效选择
cout << "Invalid choice\n";
break;
}
} while (choice != 4);
return 0;
}//end of main function