首页 > 试题广场 >

两两交换链表的节点

[编程题]两两交换链表的节点
  • 热度指数:2253 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给你一个链表,请你两两交换相邻节点,你需要真正交换节点本身,而不是修改节点的值。

两两交换示例:
链表    :1->2->3->4
交换后 :2->1->4->3


链表    :1->2->3
交换后: 2->1->3

数据范围:链表长度满足 , 链表上的值满足
示例1

输入

{1,2,3,4}

输出

{2,1,4,3}
示例2

输入

{1,2,3}

输出

{2,1,3}

说明:本题目包含复杂数据结构ListNode,点此查看相关信息
public ListNode swapLinkedPair (ListNode head) {
    if (head.next == null) return head;
    ListNode dummy = new ListNode(0); dummy.next = head;
    ListNode pre = dummy, p = head, q = head.next;
    // 穿针引线
    while (q != null) {
        // 交换操作
        p.next = q.next;
        q.next = p;
        pre.next = q;
        // 移动操作
        pre = p;
        p = p.next;
        q = p != null ? p.next : null; 
    }
    return dummy.next;
}
发表于 2021-12-30 12:32:31 回复(0)
递归求解,每次拿出链表的头两个节点组成一个小链表进行反转,后续节点继续调用这个过程,当前仅有两个节点的链表反转之后连接上递归过程返回的头结点。
import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 
     * @return ListNode类
     */
    public ListNode swapLinkedPair (ListNode head) {
        // 不足两个节点直接返回
        if(head == null || head.next == null){
            return head;
        }
        ListNode next = head.next.next;      // 把两个节点之后的链表缓存一下
        head.next.next = null;               // 断链
        head = reverseList(head);            // 反转当前仅有两个节点的链表
        head.next.next = swapLinkedPair(next);      // 这两个节点的链表反转之后连接上后续链表反转后的结果
        return head;
    }
    
    private ListNode reverseList(ListNode head) {
        ListNode prev = null;
        ListNode cur = head;
        while(cur != null){
            ListNode next = cur.next;
            cur.next = prev;
            prev = cur;
            cur = next;
        }
        return prev;
    }
}

编辑于 2022-01-08 21:31:58 回复(0)
/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 
     * @return ListNode类
     */
    ListNode* swapLinkedPair(ListNode* head) {
        // write code here
        ListNode* node = new ListNode(-1);
        node->next = head;
        ListNode* cur = node;
        // 以 1 2 3 4 为例
        // 首先cur 指向的是 -1;
        while(cur->next && cur->next->next)
        {
            // tmp 指向 1
            ListNode* temp = cur->next;
            // cur 的下一个指向的 2
            cur->next = temp->next;
            // cur 指向2
            cur = cur->next;
            // tmp 本来指向的是 2 现在转为 指向 2的下一个 3
            temp->next = cur->next;
            // cur是2 原来指向的是3 现在指向 1
            cur->next = temp;
            // cur 等于1 完成一轮转换 可以画个图 很清晰
            cur = cur->next;
        }
        return node->next;
    }
};

发表于 2022-08-23 11:58:21 回复(0)
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param head ListNode类 
# @return ListNode类
#
class Solution:
    def swapLinkedPair(self , head: ListNode) -> ListNode:
        # write code here
        new_head = ListNode(0)
        new_head.next = head

        node = new_head
        while node.next is not None:
            if node.next.next is None:
                break

            node_one = node.next
            node_two = node.next.next
            node_three = node.next.next.next

            node_one.next = node_three
            node_two.next = node_one
            node.next = node_two

            node = node_one

        return new_head.next

发表于 2024-04-21 19:15:49 回复(0)
public class Solution {
    public ListNode swapLinkedPair (ListNode head) {
        // write code here
        ListNode pre = new ListNode(0);
        pre.next = head;
        ListNode ptr = pre;
        while(ptr.next!=null){
            if(ptr.next.next == null){
                break;
            }
            ListNode a = ptr.next;
            ListNode b = ptr.next.next;
            ListNode c = ptr.next.next.next;
            ptr.next = b;
            b.next = a;
            a.next = c;
            ptr = a;
        }
        return pre.next;
    }
}

编辑于 2024-03-07 14:04:15 回复(0)
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param head ListNode类
# @return ListNode类
#
class Solution:
    def swapLinkedPair(self, head: ListNode):
        a = ListNode(0)
        a.next=head
        current = a

        # 必须有cur的下一个和下下个才能交换,否则说明已经交换结束了
        while current.next and current.next.next:
            temp = current.next  #保存节点
            temp1 = current.next.next.next

            current.next = current.next.next
            current.next.next = temp
            temp.next = temp1
            current = current.next.next
        return a.next

发表于 2024-03-02 17:19:13 回复(0)
/**
 *  #[derive(PartialEq, Eq, Debug, Clone)]
 *  pub struct ListNode {
 *      pub val: i32,
 *      pub next: Option<Box<ListNode>>
 *  }
 * 
 *  impl ListNode {
 *      #[inline]
 *      fn new(val: i32) -> Self {
 *          ListNode {
 *              val: val,
 *              next: None,
 *          }
 *      }
 *  }
 */
struct Solution{

}

impl Solution {
    fn new() -> Self {
        Solution{}
    }

    /**
    * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
    *
    * 
        * @param head ListNode类 
        * @return ListNode类
    */
    pub fn swapLinkedPair(&self, head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
        // write code here
        let mut dummy_head = Some(Box::new(ListNode::new(233)));
        dummy_head.as_mut()?.next = head;
        // println!("{}", dummy_head.as_mut()?.val);
        
        let mut p = &mut dummy_head;
        while p.is_some() && p.as_ref()?.next.is_some() && p.as_ref()?.next.as_ref()?.next.is_some() {
            let mut a = p.as_mut()?.next.take();
            let mut b = a.as_mut()?.next.take();
            let mut c = b.as_mut()?.next.take();
            p.as_mut()?.next = b;
            p = &mut p.as_mut()?.next;
            p.as_mut()?.next = a;
            p = &mut p.as_mut()?.next;
            p.as_mut()?.next = c;
        }

        dummy_head?.next
    }
}

发表于 2023-08-17 22:33:16 回复(0)

简单粗暴双指针

import java.util.*;
public class Solution {
    public ListNode swapLinkedPair (ListNode head) {
        if(head == null || head.next == null) return head;
        ListNode h = new ListNode(0);
        h.next = head;
        ListNode pre = h;
        ListNode fast = h.next.next;
        ListNode slow = h.next;
        while(fast != null) {
            slow.next = fast.next;
            pre.next = fast;
            fast.next = slow;
            pre = slow;
            slow = slow.next;
            if(slow == null) break;
            fast = slow.next;
        }
        return h.next;
    }
}
发表于 2023-05-08 16:05:56 回复(0)
struct ListNode* swapLinkedPair(struct ListNode* head ) {
    // write code here

    struct ListNode* left  = head;
    struct ListNode* right = head->next;
    struct ListNode* temp = NULL;

    if ((head == NULL) || (head->next == NULL)) return head;

    left->next = right->next;
    right->next = left;
    head = right;

    while ((left->next != NULL) && (left->next->next != NULL)) {
        temp = left;
        left = left->next;
        right = left->next;

        left->next = right->next;
        right->next = left;
        temp->next = right;
    }

    return head;
}

发表于 2023-03-10 17:54:28 回复(0)
package main
import _"fmt"
import . "nc_tools"
/*
 * type ListNode struct{
 *   Val int
 *   Next *ListNode
 * }
 */

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param head ListNode类 
 * @return ListNode类
*/
func swapLinkedPair( head *ListNode ) *ListNode {
    arr:=[]*ListNode{}
    for p:=head;p!=nil;p=p.Next{
        arr=append(arr,p)
    }
    for i:=0;i<len(arr);i+=2{
        if i+1<len(arr){
            arr[i],arr[i+1]=arr[i+1],arr[i]
        }
    }
    for i,_:=range arr{
        if i+1<len(arr){
            arr[i].Next=arr[i+1]
        }else{
            arr[i].Next=nil
        }
    }
    return arr[0]
}

发表于 2023-03-07 21:02:07 回复(0)
C++ 递归
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 
     * @return ListNode类
     */
    ListNode* swapLinkedPair(ListNode* head) {
        // write code here
        //code base
        if(head == NULL || head->next == NULL) return head;
        
         ListNode* next = head->next;
         head->next = swapLinkedPair(next->next);
         next->next = head;

         return next;
    }
};

发表于 2022-09-19 15:06:46 回复(0)
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 
     * @return ListNode类
     */
    ListNode* swapLinkedPair(ListNode* head) 
    {
        // write code here
        if(head == nullptr || head->next == nullptr)
            return head;
        
        ListNode* dummyHead=new ListNode(-1);
        dummyHead->next=head;
        ListNode* tail=dummyHead;
        while(tail->next&&tail->next->next)
        {
            ListNode* num1=tail->next;
            ListNode* num2=tail->next->next;
            tail->next=num2;
            num1->next=num2->next;
            num2->next=num1;
            tail=num1;
        }
        return dummyHead->next;
    }
};

发表于 2022-09-12 12:44:36 回复(0)
import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 
     * @return ListNode类
     */
    public ListNode swapLinkedPair (ListNode head) {
        // write code here
        ListNode res = new ListNode(-1);
        res.next = head;
        // 要交换两个节点的前一个节点
        ListNode headPre = res;
        // 后续没有两个节点不在进行交换
        while(head != null && head.next != null){
            // 要交换两个节点的其中一个(第二个,head是第一个)
            ListNode temp = head.next;
            // 要交换两个节点的后面一个节点
            ListNode tempNext = head.next.next;
            
            // 开始交换
            // 要交换两个节点的前一个节点的后面连接到交换节点的第二个
            headPre.next = temp;
            // 第二个节点后面连第一个
            temp.next = head;
            // 第一个后面连要交换两个节点的后面一个节点
            head.next = tempNext;
            
            // 移动指针
            // 前置节点移动
            headPre = head;
            // 第一个交换节点移动
            head = tempNext;
        }
        return res.next;
    }
}

发表于 2022-08-25 11:25:12 回复(0)
ListNode* swapLinkedPair(ListNode* head) {
        // write code here
        if(!head)return head;
        ListNode* res=new ListNode(0),*pre=res,*cur,*nxt;
        res->next=head;
        while(pre->next && pre->next->next){
            cur=pre->next;
            nxt=cur->next;
            ListNode* temp=nxt->next;
            pre->next=nxt;
            nxt->next=cur;
            cur->next=temp;
            pre=cur;
        }
        return res->next;
    }

发表于 2022-08-15 11:35:59 回复(0)
用一个单指针虚拟head结点进行操作
public ListNode swapLinkedPair (ListNode head) {
        if(head.next==null)return head;
        ListNode node=head.next;
        while(head!=null){
            ListNode p=null;
            if(head.next.next!=null){
                p=head.next.next;
            }
            head.next.next=head;
            if(p==null){
                head.next=null;
            }else{
                if(p.next==null){
                    head.next=p;
                    head=p;
                    break;
                }else{
                    head.next=p.next;
                }
            }
            head=p;
        }
        return node;
    }



发表于 2022-06-06 19:02:57 回复(0)
import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 
     * @return ListNode类
     */
    public ListNode swapLinkedPair (ListNode head) {
        // write code here
        ListNode dummyNode=new ListNode(-1);
        dummyNode.next=head;
        ListNode pre=dummyNode;
        ListNode cur=head,cur_next;
        while(cur!=null&&cur.next!=null){
            cur_next=cur.next;
            //反转
            cur.next=cur_next.next;
            cur_next.next=cur;
            pre.next=cur_next;
            //前进一次
            pre=cur;
            cur=cur.next;
        }
        return dummyNode.next;
    }
}

发表于 2022-05-09 17:03:27 回复(0)
import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 
     * @return ListNode类
     */
    public ListNode swapLinkedPair(ListNode head) {
        // write code here
        if (head == null || head.next == null) {
            return head;
        }

        // 虚拟头节点,方便交换head
        ListNode virtualHead = new ListNode(-1);

        virtualHead.next = head;
        ListNode previous = virtualHead;
        ListNode cur = head;
        while (cur != null && cur.next != null) {
            swap(previous, cur);
            previous = cur;
            cur = cur.next;
        }
        return virtualHead.next;
    }

    private void swap(ListNode previous, ListNode cur) {
        ListNode next = cur.next;
        cur.next = next.next;
        previous.next = next;
        next.next = cur;
    }
}

发表于 2022-04-13 18:58:37 回复(0)
/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 
     * @return ListNode类
     */
    ListNode* swapLinkedPair(ListNode* head) {
        // write code here
        typedef ListNode* List;
        if(!head || !head->next)
            return head;
        if(!head->next->next){
            List loc = nullptr;
            loc = head->next;
            head->next = nullptr;
            loc->next = head;
            return loc;
        }
          
        queue<List>ans;
        List p = head;
        List newhead = (List)malloc(sizeof(ListNode));
        List rear = newhead;
        //节点全部摘出来
        int count = 0;
        while(p){
            count++;
            ans.push(p);
            p = p->next;
        }
        
        while(!ans.empty()){
            List first = ans.front();
            List second = nullptr;
            ans.pop();
            if(!ans.empty()){
                second = ans.front();
                ans.pop();
            }
            if(first && second){
                rear->next = second;
                second->next = first;
                first->next = nullptr;
            }
            else{
                first->next = nullptr;
                rear->next = first;
            }
            rear = first;
        }
        return newhead->next;
    }
};


用一个队列先存储所有的节点
发表于 2022-02-10 15:37:49 回复(0)

递归求解即可
这里要注意自身交换和进行递归的顺序
如果先交换自身,再递归的话,代码写起来会比较麻烦
如果先递归再交换自身的话,代码写起来就轻松多了

import java.util.*;

public class Solution {

    public ListNode swapLinkedPair (ListNode head) {
        if (head==null || head.next==null) return head;
        head.next.next=swapLinkedPair(head.next.next);
        ListNode newHead = head.next;
        head.next=newHead.next;
        newHead.next=head;
        return newHead;
    }
}
发表于 2022-01-18 10:42:35 回复(0)
    def swapLinkedPair(self, head: ListNode) -> ListNode:
        # create dummy because head may be moved
        dummy = ListNode(-1)
        dummy.next = head
        prev, curr = dummy, head
        while curr and curr.next:
            # save
            curr_next_next = curr.next.next
            # reverse
            prev.next = curr.next
            curr.next.next = curr
            curr.next = curr_next_next
            # move forward
            prev = curr
            curr = curr.next
        return dummy.next

发表于 2021-11-12 17:24:32 回复(0)