LeetCode-Swap Nodes in Pairs

题目:

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 };
原文地址:https://www.cnblogs.com/sixue/p/4011605.html