Leetcode0024--Swap Nodes in Pairs 链表配对交换

【转载请注明】http://www.cnblogs.com/igoslly/p/8707274.html

 

来看一下题目:

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、这题考基础的链表结点操作,并没有多大难度,基本操作如下:

       2、循环体 p 指向调换的前一个结点,为了避免 head ==NULL 和 链表单结点的情况,设置 ListNode * res ,res->next = head 指针


 

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        ListNode * res=new ListNode(0);
        res->next=head;
        ListNode *p=res;
        while(1){
            if(p->next!=NULL&&p->next->next!=NULL){
                ListNode *pre=p,*temp;
                p=p->next;
                temp=p->next;
                p->next=temp->next;
                temp->next=p;
                pre->next=temp;
            }else{
                break;
            }
        }
        return res->next;
    }
};

 

原文地址:https://www.cnblogs.com/igoslly/p/8707274.html