美文网首页
24. 两两交换链表中的节点

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

作者: 一直流浪 | 来源:发表于2022-10-14 12:46 被阅读0次

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

    题目链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs/

    难度:中等

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

    你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

    示例:

    给定 1->2->3->4, 你应该返回 2->1->4->3.
    

    解法一:利用单指针操作

    算法思路:

    (1)创建初始化结果链表result,并创建临时指针指向result

    (2)若head!=null 并且 head.next !=null,则进入循环

    (3)创建临时指针t指向head.next.next

    (4)re.next = head.next

    (5)re = re.next

    (6)re.next = head

    (7)re.next.next = t

    (8)re = re.next

    (9)head = t

    (10)本轮循环结束,继续下一轮循环,从第(2)步开始

    (11)循环结束,re连接起来的路径,即result链表就是最后的结果链表

    图解:

    注释: (1)粉色的路径为result链表

                (2)红色的线条为当前步骤进行的改动
    
                (3)蓝色的字体为当前步骤的备注
    
                (4)红色字体为当前步骤
    

    (1)

    image.png

    (2)


    image.png

    (3)


    image.png

    (4)

    image.png

    (5)

    image.png

    (6)

    image.png

    (7)

    image.png

    代码实现:

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode swapPairs(ListNode head) {
            if(head == null || head.next == null) {
                return head;
            }
            
            ListNode result = new ListNode(0);
            ListNode re = result;
            
            while(head!=null && head.next!= null) {
                ListNode t = head.next.next;
                re.next = head.next;
                re = re.next;
                re.next = head;
                re = re.next;
                re.next = t;
                head = t;
            }
            
            return result.next; 
        }
    }
    

    相关文章

      网友评论

          本文标题:24. 两两交换链表中的节点

          本文链接:https://www.haomeiwen.com/subject/agiqwrtx.html