1. 题目原址
https://leetcode.com/problems/swap-nodes-in-pairs/
2. 题目描述
3. 题目大意
给定一个链表,交换链表中相邻两个元素的位置。即相邻的元素都要交换位置
4. 解题思路
- 定义一个ListNode节点作为头节点,然后用这个头节点连接给定链表的头。
- 再定义两个ListNode节点,用来作为临时变量交换链表中的相邻两个节点。
5. AC代码
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode cur = dummy;
ListNode l1 = null;
ListNode l2 = null;
while(cur.next != null && cur.next.next != null) {
l1 = cur.next;
l2 = cur.next.next;
l1.next = l2.next;
l2.next = l1;
cur.next = l2;
cur = l1;
}
return dummy.next;
}
}