Swap Nodes in Pairs
来源:互联网 发布:算法导论视频 百度网盘 编辑:程序博客网 时间:2024/04/29 21:00
题目:
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 as2->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.
思路:
两两进行,交换,注意设定好交换节点,防止链表断裂,或是采用递归形式
代码:
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 *first=head;ListNode *pre=head;; ListNode *second;second=first->next;//单独处理头结点first->next=second->next;second->next=first;head=second;pre=first;first=first->next;while(first!=NULL&&first->next!=NULL)//注意&&的前后顺序{second=first->next; first->next=second->next; second->next=first;pre->next=second; pre=first; first=first->next;}return head; }ListNode *swapPairs2(ListNode *head) //递归法,清晰明了 { if(!head) return NULL; if(head->next) { ListNode *temp = head, *nextHead = head->next->next; head = head->next; head->next = temp; head->next->next = swapPairs(nextHead); } 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
- verilog调试--- $test$plusargs和$value$plusargs的用法
- Count Primes
- android 开发如何做内存优化
- Delphi 2010控件安装
- 杭电 ACM HDU 1162 Eddy's picture (最短路 prim算法)
- Swap Nodes in Pairs
- OpenGL学习入门之VS2010环境配置
- 东大oj-1511: Caoshen like math
- MAC JDK版本切换
- Maven 选择性编译打包
- eclipse中查看快捷键
- Linux 网络概述
- 单例的切换场景的问题
- hdu 1558 Segment set(并查集+判断线段是否相交)