C++ 单链表就地逆置算法实现 - 代码示例
#include
typedef int ElemType;
struct LNode { ElemType data; // 数据域 LNode* next; // 指针域 };
struct LinkList { LNode *head; // 头指针(带头结点) void Create(int n); // 建立含n个结点的单链表 void Traverse(); // 遍历,并输出内容 };
void reverseList(LinkList La) { LNode *pre = La.head; // 前一个结点 LNode *cur = pre->next; // 当前结点 LNode *next = cur->next; // 下一个结点
while (next != NULL) {
cur->next = pre; // 反转指针方向
pre = cur; // 移动指针
cur = next;
next = next->next;
}
cur->next = pre; // 反转最后一个结点的指针
La.head->next = cur; // 头结点指向反转后的第一个结点
}
void LinkList::Create(int n) { head = new LNode; // 创建头结点 head->next = NULL;
LNode *cur = head;
for (int i = 0; i < n; i++) {
LNode *node = new LNode;
cin >> node->data;
node->next = NULL;
cur->next = node;
cur = node;
}
}
void LinkList::Traverse() { LNode *cur = head->next;
while (cur != NULL) {
cout << cur->data << ' '; // 将双引号改为单引号
cur = cur->next;
}
cout << endl;
}
int main() { int n; while(cin>>n) { LinkList La; La.Create(n); reverseList(La); La.Traverse(); }
return 0;
}
原文地址: http://www.cveoy.top/t/topic/pbYP 著作权归作者所有。请勿转载和采集!