24. 两两交换链表中的节点

24. 两两交换链表中的节点

题目链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs/

难度:中等

给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

示例:

给定 1->2->3->4, 你应该返回 2->1->4->3.

解法一:利用单指针操作

算法思路:

(1)创建初始化结果链表result,并创建临时指针指向result

(2)若head!=null 并且 head.next !=null,则进入循环

(3)创建临时指针t指向head.next.next

(4)re.next = head.next

(5)re = re.next

(6)re.next = head

(7)re.next.next = t

(8)re = re.next

(9)head = t

(10)本轮循环结束,继续下一轮循环,从第(2)步开始

(11)循环结束,re连接起来的路径,即result链表就是最后的结果链表

图解:

注释: (1)粉色的路径为result链表

​ (2)红色的线条为当前步骤进行的改动

​ (3)蓝色的字体为当前步骤的备注

​ (4)红色字体为当前步骤

(1)

在这里插入图片描述

(2)在这里插入图片描述
(3)在这里插入图片描述
(4)

在这里插入图片描述
(5)

在这里插入图片描述
(6)
在这里插入图片描述

(7)
在这里插入图片描述

代码实现:

在这里插入图片描述

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head == null || head.next == null) {
			return head;
		}
		
		ListNode result = new ListNode(0);
		ListNode re = result;
		
		while(head!=null && head.next!= null) {
			ListNode t = head.next.next;
			re.next = head.next;
			re = re.next;
			re.next = head;
			re = re.next;
			re.next = t;
			head = t;
		}
		
		return result.next;	
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值