反轉鍊錶2

2022-03-23 16:13:44 字數 1017 閱讀 3195

題目:

反轉從位置 m 到 n 的鍊錶。請使用一趟掃瞄完成反轉。

說明:1 ≤ m ≤ n ≤ 鍊錶長度。

示例:輸入: 1->2->3->4->5->null, m = 2, n = 4

輸出: 1->4->3->2->5->null

static listnode reverse(listnode head,int m,int

n)

/*小於m的不需要反轉

*/if(count

/*記錄反轉的第乙個節點

*/if(count==m)

/*記錄反轉末尾的後乙個節點

*/if(count==n+1)

/*大於n的不需要反轉

*/if(count>n)

/*記錄反轉末尾的節點

*/if(count==n)

count++;

/*記錄當前節點的後乙個節點

*/listnode temp=curr.next;

/*賦值當前節點的下乙個節點是臨時節點

*/curr.next=pre;

/*賦值臨時節點為當前節點

*/pre=curr;

/*當前節點賦值為下乙個節點,繼續遍歷

*/curr=temp;

}/*反轉的前乙個節點的下乙個節點賦值為反轉末尾的節點

*/if(h!=null

)

/*反轉的第乙個節點的下乙個節點為反轉末尾的後乙個節點

*/if(h1!=null

)

/*如果m不是第乙個節點則返回入參的節點

*/if(m>1)

/*返回第乙個節點

*/return pre==null?head:pre;

}

view code

@data

public

static

class

listnode

}

view code

鍊錶 反轉鍊錶

問題 兩兩交換鍊錶中的節點 問題 k 個一組翻轉鍊錶 問題鏈結 利用棧先進後出的特性,遍歷鍊錶,將每個結點加入棧中,最後進行出棧操作,先出棧的結點指向臨近的後出棧的結點。definition for singly linked list.struct listnode class solution ...

反轉鍊錶與分組反轉鍊錶

經典的反轉鍊錶,先上 public class listnode public class printlist system.out.println public class reverse public listnode reverse listnode root listnode pre nul...

鍊錶 鍊錶反轉I

package com.hnust.reversal public class listnode public listnode int value,listnode next override public string tostring 我們可以通過把鍊錶中鏈結節點的指標反轉過來,從而改變鍊錶的...