1. 首页
  2. 软件开发
  3. day-59 两两交换链表中的节点

day-59 两两交换链表中的节点

  • 发布于 2024-09-26
  • 1 次阅读


思路
只需将链表两两交换节点即可,如果是奇数个节点,最后一个节点则不用交换

解题过程
可以先自定义一个头结点thead,这样更便于思考交换,最后返回thead.next即可

Code

/**
 * 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 thead=new ListNode();
        thead.next=head;
        ListNode pre=thead;
        ListNode mid=thead.next;
        ListNode next=thead.next.next;
        while(true){

            mid.next=next.next;
            next.next=mid;
            pre.next=next;

            pre=pre.next.next;
            if(pre.next!=null) mid=pre.next;
            else break;
            if(pre.next.next!=null) next=pre.next.next;
            else break;
        }
        return thead.next;
    }
}

作者:菜卷
链接:https://leetcode.cn/problems/swap-nodes-in-pairs/solutions/2928982/liang-liang-jiao-huan-lian-biao-zhong-de-jq44/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

原文链接: https://blog.csdn.net/qq_53568730/article/details/142497000