leetCode_024 Exchange the nodes in the linked list in pairs

topic:

Given a linked list, exchange adjacent nodes in it in pairs, and return the exchanged linked list.

You can't just simply change the internal value of the node, but need to actually exchange the node.

Example:

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

Directly on the code:

        public static ListNode swapPairs(ListNode head) {
            //判断为空或者只有一个节点的情况
            if(head == null || head.next == null) return head;
            //初始化一个next节点
            ListNode next = head.next;//将next节点指向head的下一个节点
            head.next = swapPairs(next.next);//head节点指向后面进行递归操作的节点
            next.next = head;//next指向head节点
            return next;//由于next为新的头节点,返回next节点
        }

Write a test case to test:

package leetCode_024;


public class SwapPairs {
    public static class ListNode {
        int val;
        ListNode next;
        ListNode(int x) {
            val = x;
        }

        public static String print(ListNode listNode){//打印节点的方法
            StringBuilder sb = new StringBuilder();
            while (listNode!=null){
                sb.append(listNode.val);
                listNode = listNode.next;
            }
            return sb.toString();
        }
    }


        public static ListNode swapPairs(ListNode head) {
            //判断为空或者只有一个节点的情况
            if(head == null || head.next == null) return head;
            //初始化一个next节点
            ListNode next = head.next;//将next节点指向head的下一个节点
            head.next = swapPairs(next.next);//head节点指向后面进行递归操作的节点
            next.next = head;//next指向head节点
            return next;//由于next为新的头节点,返回next节点
        }


    public static void main(String[] args) {
        ListNode listNode = new ListNode(1);//新建节点1
        listNode.next = new ListNode(2);//1指向下一个节点2
        listNode.next.next = new ListNode(3);//2指向下一个节点3
        listNode.next.next.next = new ListNode(4);//3指向下一个节点4
        System.out.println(listNode.print(listNode));//1234
        listNode = swapPairs(listNode);//两两交换其中相邻的节点,并返回交换后的链表
        System.out.println(listNode.print(listNode));//2143
    }
}

To solve the problem, please visit station B https://www.bilibili.com/video/BV1pJ411s7P4?p=1

This is the end.

Guess you like

Origin blog.csdn.net/weixin_43419256/article/details/107788519