13.<tag-链表和结点的交换>-lt.24. 两两交换链表中的节点 + lt.61. 旋转链表 dbc

lt.24. 两两交换链表中的节点

[案例需求]
在这里插入图片描述

[思路分析一, 迭代法]

  • 艹, 自己半年独立写的一道题, 再写一次过不了了还. 蛋疼!

[代码实现]

// 1. 迭代解法

/**
 * 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) {
        //
        

        ListNode dummyNode = new ListNode(-1);
        dummyNode.next = head;

        ListNode temp = dummyNode;

        while(temp.next != null && temp.next.next != null){
            

            //两两交换
           ListNode cur_left = temp.next;
           ListNode cur_right = temp.next.next;

           temp.next = cur_right;

           cur_left.next = cur_right.next;

           cur_right.next = cur_left;

           temp = cur_left;
            
        }


        return dummyNode.next;
    }
}

[思路分析二, 递归法]
在这里插入图片描述

/**
 * 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) {
        if(head == null || head.next == null)return head;

        ListNode next = head.next;

        head.next = next.next;
        next.next = head;
        
        head.next = swapPairs(head.next);

        return next;
    }
}

lt.61. 旋转链表

[案例需求]
在这里插入图片描述

[思路分析]

[代码实现]

/**
 * 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 rotateRight(ListNode head, int k) {
        
        if(head == null) return head;
        
        //遍历出链表的长度
        ListNode lenNode= head;
        int count = 1;
        while(lenNode.next != null){
            count++;
            lenNode = lenNode.next;
            //lenNode 可以作为尾结点
        }

        
        //特判
        if(k % count == 0) return head;

        //找到第 count - k - 1个结点
        int j = count - (k % count);
        ListNode preNode = head;
        while(j > 1){
            preNode = preNode.next;
            j--;
        }
        //此时pre.next == 待旋转链表的第一个结点的前一个结点
        
        lenNode.next = head;
        head = preNode.next;
        preNode.next = null;


        return head;
    }
}
posted @   青松城  阅读(15)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示