leetcode【第四周】 交换节点对

问题描述:

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.


问题分析:


由问题描述可知,这是一个单链表节点位置置换的问题。首先想到创建另一个辅助链表,按顺序两个两个地读取给定的单链表上的节点,交换读取的节点追加到辅助链表的后面,最后从辅助链表的第二个节点作为返回值,于是有了解法1。接着考虑能否不创建新的节点,直接在原给定的单链表上对节点本身的指向指针进行操作,来两两交换链表中节点的顺序。容易想到,每次一次循环要涉及到的是四个节点,因为若存在四个节点,那么第二个节点的下一节点是指向第四个节点。当然,若是第四个节点为空,那么则应指向第三个节点。若无第三和第四节点,则其指向空,所以我们可以得到以下解法2.


解法1:


/**
 * 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)
            return NULL;
        if(!head->next)
            return head;
        ListNode* helper = new ListNode(0);
        ListNode* pre = head;
        ListNode* cur = helper;
        ListNode* temp = NULL;
        
        while(pre && pre->next)
        {
            cur->next = pre->next;
            temp = pre->next->next;
            pre->next->next = pre;
            pre->next = NULL;
            cur = pre;
            pre = temp;
            
        }
        if(pre)
            cur->next = pre;
        return helper->next;
    }
};

解法2:

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if(!head)
            return NULL;
        
        if(head->next)
        {
            ListNode* pre = head;
            head = head->next;
        
            ListNode* temp = NULL;
            while(pre&&pre->next)
            {
                temp = pre->next->next;
                pre->next->next = pre;
               
               
                if(temp&&temp->next)
                {
                    pre->next = temp->next;
                }else
                {
                    pre->next = temp;
                }
                pre = temp;
                
            }
        }
        return head;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值