Swap Nodes in Pairs

来源:互联网 发布:宇石网络怎么样 编辑:程序博客网 时间:2024/06/05 17:34

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.

题目:交换链表中相邻两节点的位置。

分析:链表的操作,画图分析清楚哪一步做什么,然后哪些next需要提前保存。为了统一处理修改head的问题,定义头指针。

代码:

/** * 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) {        if(head==NULL || head->next==NULL) return head;        ListNode *odd=head;//记录前后两个节点        ListNode *even=head->next;        ListNode *hhead=new ListNode(-1);//定义头指针        hhead->next=head;        ListNode *pre=hhead;//pre保存前一组pair的even指针,用于与后面的pair连接        while(odd && even){            ListNode *t=even->next;//记录下一个pair的位置            odd->next=t;            even->next=odd;//修改指向            pre->next=even;                        pre=odd;//更新odd even,及pre的位置            odd=t;            if(odd) even=odd->next;//注意偶数个节点的情况,此时odd可能为NULL            else break;        }        return hhead->next;    }};


0 0