[Leetcode] 24. 两两交换链表中的节点 java

给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。

示例:

给定 1->2->3->4, 你应该返回 2->1->4->3
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {//不设置dummyHead得到的结果是2,4 17、20行
        ListNode dummyHead=new ListNode(0);
        dummyHead.next=head;
        head=dummyHead;
        while(head.next!=null&&head.next.next!=null){
            ListNode node1=head.next;
            ListNode node2=head.next.next;
            head.next=node2;
            node1.next=node2.next;
            node2.next=node1;
            head=node1;
        }
    return dummyHead.next;
    }
}

猜你喜欢

转载自blog.csdn.net/niceHou666/article/details/83055493