链表分区稳定性说明?

时间:2020-09-08 08:16:43

标签: java data-structures linked-list

我一直在通过CTCI工作,并遇到了链接列表的这个问题:

'给出一个链表和一个值x,将一个链表划分为一个值x,这样所有小于x的节点都在所有大于或等于x的节点之前。如果x包含在列表中,则x的值仅需要在小于x的元素之后(请参见下文)。分区元素x可以出现在“右分区”中的任何位置;它不需要出现在左右分区之间,例如

Input :  3 -> 5 -> 8 -> 5 -> 10 -> 2 -> 1 
         x = 5
Output : 3-> 1-> 2-> 5-> 8-> 5-> 10

如果我们不关心使列表中的元素“稳定”,那么我正在寻找一种解决方案,但是我对此感到有些困惑。如果说稳定意味着: “具有相同或相同键的两个对象在排序输出中的显示顺序与在要排序的输入中出现的顺序相同” 那我相信下面的代码可以实现吗?下面的代码如何不稳定?谢谢!

public class Partition {    
    /* Link list Node */
    static class Node {  
        int data;  
        Node next;  
    } 
    
    // A utility function to create a new node  
    static Node newNode(int data) {  
        Node new_node = new Node();  
        new_node.data = data;  
        new_node.next = null;  
        return new_node;  
    }  
    
    /* Not stable? Breaks original order or referring to memory? */
    static Node partition(Node node, int x) { 
        Node head = node;
        Node tail = node;
                
        while (node != null){
            Node next = node.next;
            if (node.data < x){
                node.next = head;
                head = node;
            }
            else {
                tail.next = node;
                tail = node; 
            }
            node = next;
        }
        tail.next = null;
        return head;
        
    }
    
    /* Function to print linked list */
    static void printList(Node head)  
    {  
        Node temp = head;  
        while (temp != null)  
        {  
            System.out.print(temp.data + " ");  
            temp = temp.next;  
        }  
    } 

    public static void main(String []args){
        /* Start with the empty list */
        Node head = newNode(3);  
        head.next = newNode(5);  
        head.next.next = newNode(8);  
        head.next.next.next = newNode(5);  
        head.next.next.next.next = newNode(10);  
        head.next.next.next.next.next = newNode(2);  
        head.next.next.next.next.next.next = newNode(1); 
        
        int x = 5;  
        head = partition(head, x);  
        printList(head);  
    }
} 

0 个答案:

没有答案
相关问题