Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list's nodes, only nodes itself may be changed.
防止用增加值, 存储前后变量只进行值交换, 而不处理节点顺序指针的投机行为
- Example:
- Given 1->2->3->4, you should return the list as 2->1->4->3.
额外收获:
每次刷题都会发现自己一些基本的概念没有弄清,& 是其中之一
& 特别容易带给我的误解是取地址符号, 其实在某些情况 & 表示是别名
eg:int a; int &ra=a; // 定义引用 ra, 它是变量 a 的引用, 即别名
说人话: int 本小可爱; int & 小仙女 = 本小可爱;
本小可爱其实就是小仙女, 这是一个人, 但是名字只能由一个所以平时大家叫我小可爱, 但如果叫小仙女也是说我, 而且因为
本身就是一个变量 (人), 所以操作都是共荣损的, 有人给小仙女送花 = 给小可爱送花
- Opps,I suddenly notice I didn't write in English,My fault
- C11 is really a magically improve than C++ ,especially the auto.It changes this complex question
- into the simple one.It use a auxiliary variable to change the node of list
- #include <iostream>
- #include<vector>
- #include<iostream>
- #include<string>
- #include<stdio.h>
- #include<string.h>
- #include<iomanip>
- #include<vector>
- #include<list>
- #include<queue>
- #include<algorithm>
- #include<stack>
- #include<map>
- using namespace std;
- struct ListNode {
- int val;
- ListNode *next;
- ListNode(int x) : val(x), next(NULL) {}
- };
- class Solution {
- public:
- ListNode* swapPairs(ListNode* head) {
- if(!head||!head->next) return head;
- ListNode d(0);
- d.next=head;
- head=&d;
- //if we want some conditions exist directly use it,if not use !
- while(head&&head->next&&head->next->next)
- {
- auto n1=head->next;
- auto n2=n1->next;
- n1->next=n2->next;
- n2->next=n1;
- head->next=n2;
- head=n1;
- }
- return d.next;
- }
- };
- int main()
- {
- ListNode a(10);
- ListNode b(20);
- ListNode c(30);
- ListNode d(70);
- Solution s;
- a.next=&b;
- b.next=&c;
- c.next=&d;
- ListNode *head=&a;
- // while(head)
- // {
- // cout<<head->val<<endl;
- // head=head->next;
- // }
- ListNode* res=NULL;
- res=s.swapPairs(head);
- while(res)
- {
- cout<<res->val<<endl;
- res=res->next;
- }
- return 0;
- }
我必须要用中文表达下我的兴奋之情: 两个方面, 学习上和心理上
学习:
我很久之情一直不懂引用具体的含义, 有幸今天在这里面用了很多, 搞懂了我之前认为的大 boss 问题 ListNode *p=&a; 类似这样是指 ListNode 类型的指针变量指向 a 所在的地址, 我们知道, 指针是按地址来进行索引的.& 这里是取地址, 把 a 所在的地址赋值 p. 并不是引用, 引用也是一种我不熟练的知识
知道了如何构建 ListNode 链表结构, 上下节点之间该怎么连接, 怎样输出链表
膜拜 C11 的神奇性能, auto 变量简直无敌, 给交换提供了难以想象的方便
可以进步的地方:
把 ListNode 值改成可以输入的
对比 C++ python 感受
心态:
我最近特别希望进入努力的状态, 真的每天都有新的感悟和收获. 昨天的感悟是与其抱怨不如行动, 因为昨天抱怨了很久, 所以晚上睡得晚, 我就想要把这时间用来学习多好, 今天则是很紧张, 其实这是不可避免的, 因为我在强迫自己提速, 我要求自己快速做事, 动作太快人自然就会焦虑, 我一焦虑睡眠就差强人意, 我今天已经很晚了还在学, 又烦躁又焦虑就开始看搞笑视频, 看到最后我想倒头就睡但是发现睡不着, 胃也不舒服, 情绪不要太亢奋, 最好能保持一个比较平静的阶段是比较有利的, 但是我最后还是拿起了电脑并告诉我自己无论再烦, 无论无论再烦再烦, 都必须写下去, 写了, 其实, 人才能真正的宁静和放松下来, 夜很安静了, 只有我的敲键盘声, 我不喜欢用睡美容觉的时间熬夜自虐, 我只是希望在昨天 "抱怨的时间不如去努力" 的认知基础上, 让自己切肤之痛的领悟到 "焦虑不是逃避任务的借口" 无论怎么用搞笑视频逃避, 最终都逃不过, 都必须再回到这来, 回来受这一场磨难, 所以早完早好, 自己要认清
来源: http://www.bubuko.com/infodetail-3116020.html