5、 链表翻转
<1>迭代方式
Prev = head;
Curr = head;
If(head==null||head.getNext()==null){
return head
}
Node tem;
while(curr.getNext()!= null){
tmp = curr.getNext();
curr.getNext().setNext(prev);
prev = curr;
curr = tmp;
}
return curr;
2、递归方式
递归是从最后一个节点翻转。
Node reverse (Node head){
If(head==null||head.getNext()==null){
return head;
}
Node reHead = reverse(head.getNext());
head.getNext().setNext(head);
return reHead;
}
/**
* @Author GJL
* @Desription
* @Date 2017/11/22
* @Modified By:
**/
public class QuickSort{
public static void quickSort(int[] a,int low,int high){
int pos;
if(low<high){
pos = partition(a,low,high);
quickSort(a,low,pos-1);
quickSort(a,pos+1,high);
}
}
private static int partition(int[] a, int low, int high) {
int key = a[high];
int i = low;
int index= i-1;
while (i<high){
if(a[i]<key){
index = index+1;
int tem = a[index];
a[index] = a[i];
a[i] = tem;
}
i++;
}
int m = a[index+1];
a[index+1] = a[high];
a[high] = m;
return index+1;
}
public static void showAllInts(int[] a){
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}
public static void main(String[] args) {
int a [] ={2,1,8,4,6,89,978,0,345};
QuickSort.quickSort(a,0,8);
QuickSort.showAllInts(a);
}
}
private static int partition(int[] a, int low, int high) {
int key = a[low];
while(low<high){
while(low<high && a[high]>=key){
high--;
}
if(low<high){
a[low++] = a[high];
}
while(low<high && a[low]<key){
low++;
}
if(low<high){
a[high--]= a[low];
}
}
a[low]=key;
return low;
}