欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Swap Nodes in Pairs

程序员文章站 2022-03-05 08:09:35
...

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.

 

Example:

Given 1->2->3->4, you should return the list as 2->1->4->3.

 

解法:先操作head,因为要返回的值。处理完之后就开始认真翻转。画画图就知道怎么转了,不难。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        //先swap头两个
        if(head == null)return head;
        if(head.next == null)return head;
        if(head.next!=null){
            ListNode tmp = head; 
            ListNode tmpNext = head.next.next;
            head = head.next;
            head.next = tmp;
            head.next.next = tmpNext;
        }
        
        ListNode res = head.next;
        
        while(res !=null && res.next!=null && res.next.next!=null){ //这步判断是关键
            ListNode tmp = res.next;
            ListNode tmpNext = res.next.next.next;
            res.next = res.next.next;
            res.next.next = tmp;
            res.next.next.next = tmpNext;
            
            //res移位
            res = res.next.next;
        }
        return head;
        
    }
}