题目地址
https://leetcode.com/problems/swap-nodes-in-pairs/description/
题目描述
24. Swap Nodes in Pairs
Given a linked list, swap every two adjacent nodes and return its head.
Example 1:
Input: head = [1,2,3,4]
Output: [2,1,4,3]
Example 2:
Input: head = []
Output: []
Example 3:
Input: head = [1]
Output: [1]
思路
- dummy的运用.
- 每次往后走两步.
- 相互交换. head.next = n2. n1.next = n2.next. n2.next = n1.
- 交换后, head往后走一步. head = n1.
关键点
代码
- 语言支持:Java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null) {
return null;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode cur = dummy;
while (cur.next != null && cur.next.next != null) {
ListNode n1 = cur.next;
ListNode n2 = cur.next.next;
cur.next = n2;
n1.next = n2.next;
n2.next = n1;
cur = cur.next.next;
}
return dummy.next;
}
}
网友评论