首页 > 其他 > 详细

LeetCode-Swap Nodes in Pairs

时间:2014-10-08 23:45:27      阅读:323      评论:0      收藏:0      [点我收藏+]

题目:

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.

 

代码:

 1 class Solution{
 2 public:
 3       void swap(ListNode *node1,ListNode *node2){
 4             node1->next=node2->next;
 5             node2->next=node1;
 6       }
 7       
 8       ListNode* swapPairs(ListNode *head){
 9           if(head==NULL || head->next==NULL)  return head;
10           ListNode *ppre=NULL,*pre=NULL;
11           ListNode *tmp=NULL;
12           ListNode *p=head;
13           
14           while(p){
15                pre=p;
16                p=p->next;
17                if(p->next){
18                       tmp=p->next;
19                }
20                
21                if(pre==head) head=p;
22                if(ppre) ppre->next=p;
23                    
24                    ppre=pre;
25                    p=tmp;
26           }
27           return head; 
28       }
29 };

 

LeetCode-Swap Nodes in Pairs

原文:http://www.cnblogs.com/sixue/p/4011605.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!