Swap Nodes in Pairs
来源:互联网 发布:Python 加密算法 编辑:程序博客网 时间:2024/04/29 09:07
问题描述:
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4
, you should return the list as 2->1->4->3
.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
问题分析:
将链表中每一对结点对换,采用递归求解,直接模拟就可以
问题求解:
/** * 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 || head->next == NULL) return head; ListNode *grandChild = swapPairs(head->next->next); ListNode *Child = head->next; head->next = grandChild; Child->next = head; return Child; }};
/** * 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 || head->next == NULL){ return head; } ListNode* newHead = new ListNode(0); newHead->next = head; ListNode* preNode = newHead; ListNode* curNode = head; while(curNode != NULL && curNode->next != NULL) { // swap curNode and curNode->next preNode->next = curNode->next; curNode->next = preNode->next->next; preNode->next->next = curNode; //此处我写成 curNode = preNode->next->next, 编译不通过,对链表的操作还是有些不清楚 // go over two nodes preNode = curNode; curNode = curNode->next; } head = newHead->next; delete newHead; return head; }};
0 0
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes In Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- C++错误
- jq选项卡&&js选项卡
- 阶乘计算
- 取给定正整数的指定bit位开始的指定长度的数据 将整数拆分成bit位表示的形式
- android开发代码之隐藏软键盘
- Swap Nodes in Pairs
- 您还在打工吗?
- html5坦克大战中坦克移动代码。
- bzoj2243【SDOI2011】染色
- RuntimeDefinition
- ASP.NET性能优化
- java 多线程浅入浅出学习笔记
- javascript中apply()和call()的区别
- 关于gitlab,gerrit