链表反转
来源:互联网 发布:大数据上市公司有几家 编辑:程序博客网 时间:2024/06/17 00:19
在知乎上看见浙大查重被查了这道题,写了一下。面试常见的一道题。
原链表:head->1->2->3->null
方法:遍历一次,头插法重新排列。
head->null
head->1->null
....
head->3->2->1->null
#include <iostream>#include <vector>#include <string>using namespace std;typedef struct ListNode {int val;ListNode *next;ListNode(int x) : val(x), next(NULL) {}}ListNode;ListNode *fun(ListNode *head){ListNode *cur = head->next;//原链表节点head->next = NULL;while (cur)//重新头插法{ListNode *behind = cur->next;ListNode *temp = cur;//temp和cur绑定 temp变了 cur也变了temp->next = head->next;head->next = temp;cur = behind;/*ListNode *behind = cur->next;cur->next = head->next;head->next = cur;cur = behind;*/}return head;}int main(){ListNode *head = new ListNode(0);ListNode *n1=new ListNode(1);ListNode *n2=new ListNode(2);ListNode *n3=new ListNode(3);head->next = n1; n1->next = n2; n2->next = n3;ListNode *hhh = fun(head);ListNode *h = hhh->next;while (h){cout << h->val << endl;h = h->next;}_getch();return 0;}
阅读全文
0 0
- 链表反转
- 反转链表
- 单向链表反转
- 链表反转:
- 链表的反转
- 链表反转
- 反转单向链表
- 链表反转
- 单向链表反转
- 单向链表反转
- 链表的反转
- 链表反转
- 反转链表
- 链表反转
- 链表反转
- 链表反转
- 链表反转
- 链表的反转
- hadoop-hdfs简介(一)
- 做leetcode之Sum Root to Leaf Numbers的感悟
- static final 和 final
- LeetCode.228 Summary Ranges
- 扩展CRT&&扩展lucas
- 链表反转
- 《机器学习实战》笔记之七——利用AdaBoost元算法提高分类性能
- JS特殊函数(Function()构造函数、函数直接量)区别介绍
- Spring源码分析——BeanFactory体系之接口详细分析
- Java并发编程札记-(五)JUC容器-02CopyOnWrite
- [日常训练] God Knows
- Imagenomic Professional Plugin Suite for Mac(ps磨皮降噪滤镜套装)附注册码 v1414破解版
- 放弃sublime,使用intellij编写react native
- Java入门之Java简介