编程语言
首页 > 编程语言> > 力扣-24题(Java)-链表节点交换

力扣-24题(Java)-链表节点交换

作者:互联网

题目链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs/
题目如下:
在这里插入图片描述
在这里插入图片描述
思路:
在这里插入图片描述

/**
 * 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) {
        //tip:
        //1、当整个操作过程中,头节点会发生变动时,可增加一个虚拟节点
        //2、操作中三个指针普遍适用
        //3、链表按着顺序来,从后往前,确保不会出错
        //4、链表题要画图
        if(head==null||head.next==null) return head;//链表中元素仅有0或1个

        ListNode dummyhead=new ListNode(0);
        dummyhead.next=head;
        ListNode p=dummyhead; 

        while(p.next!=null&&p.next.next!=null){
            ListNode node1=p.next;//链表节点数>=2个
            ListNode node2=p.next.next;
            System.out.println(node1.val);

            
            node1.next=node2.next;
            node2.next=node1;
            p.next=node2;
            //dummyhead->node1->node2 before
            //dummyhead->node2->node1 after

            p=node1;
        }
        
        return dummyhead.next;
        
    }
}

标签:24,dummyhead,ListNode,val,next,链表,node1,Java,node2
来源: https://blog.csdn.net/qq_40467670/article/details/117716924