8-- problem list by a certain value of the one-way linked list into smaller left, center are equal, the right side of the large form (Elementary)

topic

Given a singly linked list head node head, and an integer pivot.

Implement a function to adjust the list, the list will be adjusted to be smaller than the left pivot portion, an intermediate equal, greater than the right side of the pivot. No more requests for the node order adjusted

List 9-> 0-> 4-> 5-> 1 pivot = 3
Adjusted: 1-> 0-> 4-> 9-> 5, may be 0-> 1-> 9->> 5- 4 regardless of the order

Thinking 

Solution ordinary time complexity is O (N), the additional space complexity O (N), the specific process is as follows:

  1. Traverse the list to obtain the list of length N
  2. Generating Node length N nodeArr array type, then traverse a linked list, and the node of the first put nodeArr
  3. In order to adjust nodeArr
  4. The nodes are sequentially connected nodeArr

Source

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

public Node listPartition1(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);
	for(i=1;i!=nodeArr.length;i++){
		nodeArr[i-1].next=nodeArr[i];
	}
	nodeArr[i-1].next=null;
	return nodeArr[0];
}

public void arrPartition(Node[] nodeArr,int pivot){
	int small=-1;
	int big=nodeArr.length;
	int index=0;
	while(index!=big){
		if(nodeArr[index].value<pivot){
			swap(nodeArr,++small,index++);
		}else if(nodeArr[index].value==pivot){
			index++;
		}else{
			swap(nodeArr,--big,index);
		}
	}
}
public void swap(Node[] nodeArr,int a,int b){
	Node tmp=nodeArr[a];
	nodeArr[a]=nodeArr[b];
	nodeArr[b]=tmp;
}

 

Published 43 original articles · won praise 21 · views 4912

Guess you like

Origin blog.csdn.net/flying_1314/article/details/103871951