2022-1-2 1721. 交换链表中的节点 143. 重排链表

这篇博客探讨了两种链表操作问题。第一个是交换链表中的节点,考虑了特殊情况如只有一个节点、正数第k个节点与倒数第k个节点相同的情况。第二个是重排链表,通过快慢指针找到链表中点,然后反转后半部分并进行头插法重组,实现链表的重新排列。
摘要由CSDN通过智能技术生成

1721. 交换链表中的节点

/**
 * 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 swapNodes(ListNode head, int k) {
        int n=0;
        ListNode c=head;
        while(c!=null){
            n++;
            c=c.next;
        }
        //卡住的原因:特殊情况没有考虑全面
        //1.链表只有一个节点时
        //2.正数第k个节点和倒数第k个节点是同一个节点时
        if(n==1 || (n-k)==(k-1)) return head;
        //倒数第k个节点 n-k
        int temp1=0;
        int max1=Math.max(n-k,k-1);
        int min1=Math.min(n-k,k-1);
        ListNode cur=head;
        ListNode temp=null;
        for(int i=0;i<max1;i++){         
            if(i==min1){
                temp1=cur.val;
                temp=cur;
            }
            cur=cur.next;
        }
        temp.val=cur.val;
        cur.val=temp1;
        return head;
    }
}

143. 重排链表

/**
 * 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 void reorderList(ListNode head) {
        //自己做时特殊情况忘记了考虑
        if(head==null || head.next==null ||head.next.next==null) return;
      
        //找中点时采用快慢指针的办法
        //找中点,链表分成两个
    ListNode slow = head;
    ListNode fast = head;
    while (fast.next != null && fast.next.next != null) {
        slow = slow.next;
        fast = fast.next.next;
    }
    ListNode newHead = slow.next;
    slow.next = null;


        ListNode new1=reverse(newHead);
        ListNode x=head;
        //采用头插法重组链表
        while(new1 != null){
            ListNode te=new1.next;
           new1.next=x.next;
           x.next=new1;
            x=new1.next;
           new1=te;
        }
        
    }
   public ListNode reverse(ListNode head) {
        ListNode temp = null;
        ListNode cur = head;
        ListNode pre = null;
        while(cur != null){
            temp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = temp;
        }
        return pre;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值