原题链接: 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;
}
}