leetcode 24 Swap Nodes in Pairs

来源:互联网 发布:手机rmvb视频剪辑软件 编辑:程序博客网 时间:2024/06/05 00:27

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 maynot 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,*f,*temp;
        if(head!=NULL&&head->next!=NULL)
        {
            p=head;
            q=head->next;
            temp=q->next;
            head=q;
            q->next=p;
            p->next=temp;
            f=head->next;
        }
        else
        {
            return head;
        }
        while(f->next!=NULL&&f->next->next!=NULL)
        {
            p=f->next;
            q=f->next->next;
            temp=q->next;
            f->next=q;
            q->next=p;
            p->next=temp;
            f=p;
        }
        return head;
    }
};

需要注意的是,在这道题中没有头节点,head所指向的节点为第一个节点而不是头节点。

0 0