LeetCode 24. Swap Nodes in Pairs
原题链接
简单
作者:
Ccc1Z
,
2020-07-15 17:53:31
,
所有人可见
,
阅读 457
思路:
- 根据题意画图
- 分析出要两两交换节点首先头节点会被交换,所以引入dummy
- 再一个分析得出需要三个指针 pre cur next
- 再根据画图来分析三个指针的交换次序
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null)
return head;
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode pre = dummy;
ListNode cur = head;
while(cur != null && cur.next != null){
ListNode next = cur.next;
cur.next = next.next;
next.next = cur;
pre.next = next;
pre = cur;
cur = pre.next;
}
return dummy.next;
}
}