【leetcode每日一题】24.Swap Nodes in Pairs

来源:互联网 发布:上海知恩服饰有限公司 编辑:程序博客网 时间:2024/05/01 20:04
题目:

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.

解析:定义三个节点temp、first和second,temp指向上一节点,first指向当前节点,second指向下一节点。让temp指向second,first指向second的下一节点,second指向first。然后依次遍历整个链表即可。代码如下:

/** * 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 *first=head;        ListNode *second=first->next;        ListNode *temp=first;        head=second;        while(first!=NULL&&second!=NULL)        {            temp->next=second;            first->next=second->next;            second->next=first;            temp=first;            first=first->next;            if(first!=NULL)                second=first->next;        }        return head;    }};


0 0
原创粉丝点击