[leetcode024] Swap Nodes in Pairs 解题报告

Swap Nodes in Pairs


Problem

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->3->4,返回结果为链表2->1->4->3。
要求:算法的空间发杂度为O(1),算法只能修改结点,不能修改链表中的值。


思路

此题目考察的是线性链表的插入和删除,为了便于操作,给链表加上头结点,操作完成之后,将该结点删除。


代码(C++)
/**
 * 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 && head->next){
            //为了便于操作,加一个空的头节点
            ListNode* node = new ListNode(-1);
            node->next = head;
            head = node;//此处注意保存头指针
            while (node->next && node->next->next)
            {
                ListNode* node1 = node->next;
                //删除结点
                node->next = node1->next;
                //将删除的结点插入到它的后一个结点后面
                node1->next = node->next->next;
                node->next->next = node1;
                node = node1;
            }
            //删除头结点
            node = head;
            head = head->next;
            delete node;
        }
        return head;
    }
};

运行结果

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值