Leetcode Problem24

Swap Nodes in Pairs

问题描述:给定一个链表,将每两个相邻的节点交换位置,返回新的链表。

这道题其实就是节点之间的交换问题,要注意保持链表的连续性,实现起来并不是很难。

    ListNode* swapPairs(ListNode* head) {
        if(head==NULL||head->next==NULL) return head;
        ListNode *p=head,*q=head->next,*tmp,*front;
        while(p!=NULL&&q!=NULL)
        {
            //头节点的情况
            if(p==head)
            {
                tmp=q->next;
                p->next=tmp;
                q->next=p;
                head=q;
            }
            //其他情况
            else
            {
                tmp=q->next;
                p->next=q->next;
                q->next=p;
                front->next=q;
            }
            front=p;
            p=p->next;
            if(p==NULL) break;
            q=p->next;
        }
        return head;
    }

beats 100.00 % of cpp submissions.

猜你喜欢

转载自blog.csdn.net/vandance/article/details/82154352