逆置单链表
问题描述:实现算法,将一个单链表逆置。(将一个单链表中的所有节点按照逆序存放)
分析:将一个单链表逆置其实就是用头插法建立单链表。定义一个空链表,分别将元单链表中的第一个节点、第二个节点一直到第n个节点插入新单链表的头部,即插入的节点成为新单链表的第一个节点。
// 假设链表节点的数据域包含学号、姓名、地址
#include <iostream>
#include <string>
using namespace std;
struct node
{
int no;
string name;
string addr;
node* next;
};
node* createList();
node* reverseList(node*);
void dispList(node*);
int main()
{
node *head{createList()};
dispList(head);
head = reverseList(head);
dispList(head);
return 0;
}
node* createList()
{
node *head{nullptr}, *pre, *cur; // head表示表头,pre表示当前插入新节点前的最后一个节点
int n;
cout << "请输入节点个数" << endl;
cin >> n;
for (int i{}; i < n; i++) {
cur = new node;
cur->next = nullptr;
if (!head) { // 若head为NULL
head = cur; // 则将第一个节点指针赋给head
} else {
pre->next = cur; // 否则,将新节点连接入链表内(插入至链表尾部)
}
cin >> cur->no >> cur->name >> cur->addr;
pre = cur;
}
return head; // 返回头指针
}
node* reverseList(node* h)
{
node* hh{new node};
hh->next = nullptr;
for (node *p{h}, *pre; p; ) { // p指向原单链表的第一个节点
pre = p; // pre指向待插入的节点
p = p->next; // p指向当前的下一个节点
pre->next = hh->next; // 将hh->next赋给pre->next, 将pre连接至逆置后单链表的原节点
hh->next = pre; // 将pre插入逆置后的单链表
}
return hh->next; // 返回逆置后单链表的头指针
}
void dispList(node* h)
{
cout << "学号\t" << "姓名\t" << "地址" << endl;
for (node* p{h}; p; p = p->next) {
cout << p->no << "\t" << p->name << "\t" << p->addr << "\t" << endl;
}
}