[LeetCode] 24. Swap Nodes in Pairs

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

1. 题目介绍

Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list’s nodes, only nodes itself may be changed.

给定一个链表,将链表中的元素两两交换。也就是每遇到2个元素,就交换这两个元素,再接着去交换下一对元素。
不可以只交换链表节点的 val 值,而应该改变链表本身。

Example:

Given 1->2->3->4, you should return the list as 2->1->4->3.

2. 解题思路

这道题非常适合用来熟悉链表的操作,可以算是入门基本题之一。题目中要求实现交换2个链表节点的功能。建议先画一个图,根据图来操作。
current是当前节点,要交换的节点是current的后面第一个节点(temp1)以及后面第二个节点(temp2)。
遍历链表时,需要每两个元素跳跃一次地进行遍历。

实现代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
		ListNode assist = new ListNode(0);
		assist.next = head;
		
		ListNode current = assist;
		while(current.next != null && current.next.next != null) {
			ListNode temp1 = current.next;//temp1是要交换的第一个节点
			ListNode temp2 = current.next.next;//temp2是要交换的第二个节点
			
			temp1.next = temp2.next;
			temp2.next = temp1;
			current.next = temp2;
			
			current = current.next.next;
		}
		return assist.next;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值