likes
comments
collection
share

【每日一道算法题】重排链表

作者站长头像
站长
· 阅读数 7

【每日一道算法题】重排链表

题解1:类似于暴力破解
通过数组存储链表元素
利用数组的指针特性重新建立需要的链表

解法一:暴力破解

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
import java.util.*;
public class Solution {
    public void reorderList(ListNode head) {
        if(head == null) return;
        LinkedList<ListNode> list = new LinkedList<>(); 
        ListNode temp = head;
        while(temp!=null){
            list.add(head);
            temp=temp.next;
        }
        int i=0,j=list.size()-1;
        while(i<j){
            list.get(i).next=list.get(j);
            i++;
            if(i==j){
                break;// 若链表长度为偶数的情况下则会提前相遇,此时已达到题目要求,直接终止循环
            }
            list.get(j).next=list.get(i);
            j--;
        }
        list.get(i).next=null;// 最后一个节点的下一个节点为null
        
    }
}
题解2
将链表分成两个链表,并将后半部分翻转,接着连接两个链表

解法二:拆分链表

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
import java.util.*;
public class Solution {
    public void reorderList(ListNode head) {
        if(head == null||head.next==null||head.next.next==null) return;
      //快慢指针找中间节点
        ListNode slow=head;
        ListNode fast=head.next;
        while(fast !=null && fast.next!=null){
            slow=slow.next;
            fast=fast.next.next;
        }
        
        ListNode mid = slow.next;
        slow.next=null;
        ListNode newHead= reverse(mid);
        
        while(newHead!=null){
            ListNode temp =newHead.next;
            newHead.next=head.next;
            head.next=newHead;
            head=newHead.next;
            newHead=temp;
        }
    }
    
    public ListNode reverse(ListNode head){
        if(head == null)
            return head;
        ListNode pre=null;
        ListNode temp=null;
        while(head!=null){
            temp=head.next;
            head.next=pre;
            pre=head;
            head=temp;
        }
        return pre;
    }
}