剑指offer:输入一个链表,反转链表后,输出链表的所有元素。
2015-09-05 00:03
441 查看
代码实现:
[code]#include <stdio.h> #include <iostream> #include <vector> using namespace std; struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } }; class Solution { public: ListNode* ReverseList(ListNode* pHead) { ListNode* pNewHead = pHead; ListNode* pNodeNext = pHead->next; ListNode* pNodePre = pHead; if(pHead == NULL) { return NULL; } pNewHead->next = NULL; while(1) { if(pNodeNext == NULL) { break; } pNodePre = pNewHead; pNewHead = pNodeNext; pNodeNext = pNodeNext->next; pNewHead->next = pNodePre; } return pNewHead; } }; int main() { ListNode* head = NULL; ListNode* temp = NULL; ListNode* newNode = NULL; int i = 0; Solution s; head = (ListNode*)malloc(sizeof(ListNode)); head->next = NULL; head->val = 1; temp = head; for(i = 2; i < 6; i++) { newNode = (ListNode*)malloc(sizeof(ListNode)); newNode->next = NULL; newNode->val = i; temp->next = newNode; temp = newNode; } temp = head; while(temp) { cout << temp->val << " " ; temp = temp->next; } cout << endl; head = s.ReverseList(head); temp = head; while(temp) { cout << temp->val << " " ; temp = temp->next; } cout << endl; return 0; }
相关文章推荐
- web前端开发工程师需要学习的技能
- CSS知识点总结2
- JSP执行过程
- JS基础
- JavaScript中常用的函数以及基础写法汇总
- AngularJS的双向数据绑定
- Caffe学习:使用pycaffe绘制loss、accuracy曲线
- SGU 194. Reactor Cooling【无源汇上下界最大流】
- 剑指offer:输入一个链表,输出该链表中倒数第k个结点。
- 解决jsp页面汉字乱码问题
- 剑指offer 调整数组顺序使奇数位于偶数前面
- 条款10:令operator=返回一个reference to * this(Have assignment operators return a reference to *this)
- Caffe学习:使用pycaffe生成mean_file.py文件
- Javascript高级程序设计——this、闭包、函数表达式
- 自定义缓存工具类----sharedPreferences
- htc支持CSS3
- 2015前端各大框架比较(angular,vue,react,ant)
- html语义化
- jQuery复习笔记
- JavaScript基础知识