LeetCode 24. Swap Nodes in Pairs (两两交换链表中的节点)
题目标签:Linked List
题目给了我们一组 linked list,让我们把每对nodes 互换位置。
新键一个dummy node,然后遍历list,每次建立 s1 和 s2 记录两个点,然后互换位置,具体看code。
Java Solution:
Runtime: 0 ms, faster than 100 %
Memory Usage: 34 MB, less than 100 %
完成日期:05/22/2019
关键点:换位置时候先后顺序
/** * 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 dummy = new ListNode(0); dummy.next = head; ListNode p = dummy; while(p.next != null && p.next.next != null) { ListNode s1 = p.next; ListNode s2 = p.next.next; // step 1: p -> s2 p.next = s2; // step 2: s1 -> s2.next s1.next = s2.next; // step 3: s2 -> s1 s2.next = s1; // step 4: p = s1 p = s1; } return dummy.next; } }
LeetCode 题目列表 - LeetCode Questions List
题目来源:https://leetcode.com/