struct Node { int data; Node *next; };
方法一:就地逆序
主要思路:在遍历链表的时候,修改当前结点的指针域的指向,让其指向前驱结点。
为此,需要用三个指针变量分别指向当前结点、前驱结点、后继结点。遍历完所有的结点后,即可以完成指针的逆序。最后,让头节点的指针域指向原来最后一个元素结点。
void reverse(Node* head) {
if (head->next == NULL) return;
Node* pre = NULL; Node* cur = head->next; Node* next;
while (cur) { next = cur->next; cur->next = pre; pre = cur; cur = next; } head->next = pre; }
方法二:插入法
主要思路:从链表的第二个结点开始,把遍历到的结点插入到头结点的后面,直到遍历结束。
void reverse(Node* head) { if (head->next == NULL) return; Node *cur, *next; cur = head->next->next;//cur初始指向第二个结点(不包括头结点) head->next->next = NULL; while (cur) { next = cur->next; cur->next = head->next; head->next = cur; cur = next; } }