leetcode 24. 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.

方法解答:

/**
 * 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) 
    {
        ListNode *p,*q,*tail;
        p=q=head;
        
        if(head==NULL || head->next==NULL)
        return head;
        
        q=head->next;
        head=q;
        p->next=q->next;
        q->next=p;
        
        tail=p;
        while(tail->next != NULL)
        {
            p=p->next;
            q=p->next;
            
            if(p && q)
            {
                tail->next=q;
                p->next=q->next;
                q->next=p;
            }
            
            tail=p;
        }
 
        return head;
    }
};


阅读更多
个人分类: leetcode
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

leetcode 24. Swap Nodes in Pairs

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭