24. Swap Nodes in Pairs
来源:互联网 发布:录音软件 比特率 编辑:程序博客网 时间:2024/05/17 10:05
这道题意思是,给出一个链表,把每一对相邻节点交换,并且不允许改变节点内部的val值,空间复杂度是常量级。
我定义了三个指针abc,b和c指向要交换的两个节点,a指向要交换的那一对节点的前面一个节点。每次交换b和c,然后把a更新到b(注意交换完了之后,后面的节点变成b而不是c了)
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode* swapPairs(ListNode* head) { if(head == NULL) return NULL; if(head->next == NULL) return head; ListNode* newhead = new ListNode(-1); newhead->next = head; ListNode* a = newhead; ListNode* b = newhead->next; ListNode* c = newhead->next->next; while(a != NULL && b != NULL && c != NULL){ cout << a->val << " "<< b->val << " "<< c->val << endl; a->next = c; b->next = c->next; c->next = b; a = b; b = a->next; c = (b == NULL)?NULL:b->next; } return newhead->next; }};
看到有更简单的代码,方法一样的:
class Solution {public: ListNode* swapPairs(ListNode* head) { ListNode *dummy = new ListNode(-1), *pre = dummy; dummy->next = head; while (pre->next && pre->next->next) { ListNode *t = pre->next->next; pre->next->next = t->next; t->next = pre->next; pre->next = t; pre = t->next; } return dummy->next; }};还有用递归做的,更简单:
class Solution {public: ListNode* swapPairs(ListNode* head) { if (!head || !head->next) return head; ListNode *t = head->next; head->next = swapPairs(head->next->next); t->next = head; return t; }};
阅读全文
0 0
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24.Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 结构体排序,sort排序,c++sort
- 小甲鱼python视频的笔记【斜杠派】
- Ubuntu14.04更换源方法以及常见问题
- JSP页面传参中文乱码
- 图像分析:二值图像连通域标记-基于行程的标记方法
- 24. Swap Nodes in Pairs
- 笨方法学习Python-习题32: 循环和列表
- C语言中字符串常量和字符常量的区别
- 剑指offer 44 左旋转字符串
- python easy install不是内部或外部命令,也不是可执行的程序
- 【WebService】使用JDK开发WebService(二)
- 【算法】分而治之(DivideAndConquer) -- C++源代码(VS2015)
- Hibernate+boostrapTable分页查询(——前台)
- Python利用WMI实现ping命令