您的位置:首页 > 编程语言 > C语言/C++

C++单向链表反转

2016-03-22 12:03 423 查看

C++单向链表反转

基本原理

遍历一遍链表,当访问到下一个节点时,将当前指针块与上一块指针块相连。

根据我的理解,我这里用到用到三个指针

假设有如下链表:



新建三个指针,信息分别如下:



*Head、*Curr都指向List,而*Temp指向一个空块

然后将Curr移动到下一块链表,这时将Head->Next指向Temp



最后移动Temp到Head,再将Head移动到Curr,整个过程大概就这样:



代码如下:

Node* My_reverse(Node *head) {
if (head == NULL) {
return head;
}
Node* temp = NULL;
Node* current_node = head;
while(current_node->next != NULL) {
current_node = current_node->next;
head->next = temp;
temp = head;
head = current_node;
}
head->next = temp;
return head;
}


整个测试代码如下:

#include <iostream>
using namespace std;

struct Node {
int num;
Node* next;
Node(int a = 0) {
num = a;
next = NULL;
}
};

Node* My_reverse(Node *head) { if (head == NULL) { return head; } Node* temp = NULL; Node* current_node = head; while(current_node->next != NULL) { current_node = current_node->next; head->next = temp; temp = head; head = current_node; } head->next = temp; return head; }

int main() {
Node *temp = new Node();
Node *tail = temp;
for (int i = 1; i < 5; i++) {
Node *new_node = new Node(i);
tail->next = new_node;
tail = new_node;
}
Node *a = temp;
while (a != NULL) {
cout << a->num << ' ';
a = a->next;
}
cout << endl;
a = My_reverse(temp);
while (a != NULL) {
cout << a->num << ' ';
a = a->next;
}
cout << endl;
return 0;
}


输出结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: