将单向链表按某值划分为左边小、中间相等、右边大的形式

思路就是将链表转换为数组,然后利用快速排序的思想解决,不过一直显示算法超时,需要再优化。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

class Node{
    int val;
    Node next;
    public Node(int val){
        this.val = val;
    }
}

public class Main{
    public static Node listPartition(Node head, int pivot){
        if (head == null) {
            return head;
        }
        Node cur = head;
        int i = 0;
        while(cur != null){
            i++;
            cur = cur.next;
        }
        Node[] nodeArr = new Node[i];
        i = 0;
        cur = head;
        for(i = 0; i < nodeArr.length; i++){
            nodeArr[i] = cur;
            cur = cur.next;
        }

        arrPartition(nodeArr, pivot);

        int len = nodeArr.length;
        for (i = 0; i < len - 1; i++) {
            nodeArr[i].next = nodeArr[i + 1];

        }

        nodeArr[len - 1].next = null;
        return nodeArr[0];
    }

    public static void arrPartition(Node[] nodeArr, int pivot){
        int a = -1;

        int b = nodeArr.length;

        int index = 0;

        while(index != b){ // 这里for不好判断
            if (nodeArr[index].val < pivot) {
                swap(nodeArr, index++, ++a);
            } else if (nodeArr[index].val == pivot) {
                index++;
            } else {
                swap(nodeArr, index, --b);
            }
        }
    }

    public static void swap(Node[] nodeArr, int a, int b){
        Node tmp = null;
        tmp = nodeArr[a];
        nodeArr[a] = nodeArr[b];
        nodeArr[b] = tmp;
    }

    public static void main(String[] args) throws IOException{
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        String[] argument = bf.readLine().split(" ");
        int num = Integer.parseInt(argument[0]);
        int pivot = Integer.parseInt(argument[1]);

        String[] elements = bf.readLine().split(" ");
        Node head = new Node(Integer.parseInt(elements[0]));
        Node cur = head;
        for (int i = 1; i < elements.length; i++){
            cur.next = new Node(Integer.parseInt(elements[i]));
            cur = cur.next;
        }

        Node res = listPartition(head, pivot);
        while(res != null){
            System.out.println(res.val);
            res = res.next;
        }
    }
}

你可能感兴趣的:(算法与数据结构)