链表真的是有点转不过来,今天又做了一道链表题,调了半天问题也没解决,先放着,提醒自己记得解决。
public static ListNode minSequenceListNode(ListNode head){
if (head.next==null) {
return head;
}
//用来统计链表总节点数
int count =1;
ListNode tmp = head;
while (tmp.next != null) {
count++;
tmp = tmp.next;
}
ListNode newL = null;
int n =1;
for (int k=0;k<count;k++){
ListNode newList = minSequence(head,k,count);
display(newList);
System.out.println();
ListNode cur = newList;
ListNode curN = new ListNode(-1);
ListNode pre = curN;
while (cur != null&& cur.next!=null) {
if (cur.val>cur.next.val){
curN=null;
n=0;
break;
}else {
curN.next = cur;
curN = curN.next;
n++;
// display(curN);
}
if (n == count) {
newL = curN;
break;
}
cur = cur.next;
}
}
return newL;
//display(newL);
}
//重排链表
public static ListNode minSequence(ListNode head,int k,int count){
ListNode cur = head;
while (cur.next != null) {
cur = cur.next;
}
k%=count;
if (k == 0) {
return head;
}
cur.next = head;
for (int i=0;i<count-k;i++){
cur = cur.next;
}
ListNode newHead = cur.next;
cur.next = null;
return newHead;
}