C++笔试题之实现单链表反转
2018-02-01 15:39
633 查看
链表反转在面试中经常容易被问及,比如:
输入 1 2 3 4 5 6 7 8 9 10
输出 10 9 8 7 6 5 4 3 2 1
输入 1 2 3 4 5 6 7 8 9 10
输出 10 9 8 7 6 5 4 3 2 1
#include <iostream> using namespace std; struct Node{ int data; Node* next; }; void Display(Node *head)// 打印链表 { if (head == NULL) { cout << "the list is empty" << endl; return; } else { Node *p = head; while (p) { cout << p->data << " "; p = p->next; } } cout << endl; } Node* ReverseList(Node* head)// 反转链表 { if (head == NULL) return NULL; Node* cur = head; Node* pre = NULL; Node* nex = NULL; while (cur->next != NULL) { nex = cur->next; cur->next = pre; pre = cur; cur = nex; } cur->next = pre; return cur; } Node* Init(int num) // 创建链表 { if (num <= 0) return NULL; Node* cur = NULL; Node* head = NULL; Node* node = (Node*)malloc(sizeof(Node)); node->data = 1; head = cur = node; for (int i = 1; i < num; i++) { Node* node = (Node*)malloc(sizeof(Node)); node->data = i + 1; cur->next = node; cur = node; } cur->next = NULL; return head; } int main( ) { Node* list = NULL; list = Init(10); Display(list); Node* newlist = ReverseList(list); Display(newlist); system("pause"); return 0; }
相关文章推荐
- c++实现单向链表反转的学习总结
- C++将链表反转的实现
- 反转链表 C++实现
- 剑指offer第十五题【反转链表】c++实现
- C++递归与非递归实现链表的反转
- C++笔试题之实现字符串反转
- c++实现链表反转
- 【编程题目】反转链表(C++实现)
- C++实现链表逆序打印、链表反转
- 剑指offer刷题之c++实现的反转链表
- 递归,迭代,堆栈三种方式实现单链表反转(C++)
- C/C++面试程序题(一)——字符串反转、链表反转的递归、非递归实现
- leetcode之83. Remove Duplicates from Sorted List(C++实现 链表去重)
- 使用C++实现的单向循环链表
- C++模板链表实现优先级队列
- [互联网面试笔试汇总C/C++-8] 寻找两个链表的第一个交点-微策略
- 数据结构(6)线性表之链表C++实现交集
- C++ 递归和非递归实现链表逆序
- C++实现复杂链表
- 用C++实现链表版本通讯录