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;
}
输出结果:
相关文章推荐
- C++ delete[] 是如何知道数组大小的?
- c++四种强制类型转换
- C语言中free函数如何确定释放的空间大小
- C++中使用指针、引用进行参数传递
- C++中定义一个数组一定要给出长度吗?
- 【c++】龟兔赛跑问题
- 【c++】龟兔赛跑问题
- c++ 抽象类
- 浅谈 C++ 中的 new/delete 和 new[]/delete[]
- c++: 获取delete[]中的数组大小
- C语言第四篇:指针的辨析
- 链表实例(C语言)
- c++11 学习及测试(constexpr,using,default构造函数,lamada表达式)
- 十六进制字符串转字节序列
- 算法-求二进制数中1的个数
- c++ 浅拷贝 深拷贝
- __cplusplus
- C++ 内存池 -- C++ Memory Pool
- C语言 字符串操作两头堵模型
- MFC UpdateData