標籤:
主要是面試中可能會經常碰上該類似操作,尤其是稍大點公司,面試官可能並不在乎你能不能搞定該題,但是這類型題目最是能體現程式員的思維狀態 ---一個迷糊頭腦的程式員 怎能立志改變這個世界
/** * @author luochengcheng * 定義一個單鏈表 */class Node {//變數private int record;//指向下一個對象private Node nextNode;public Node(int record) {super();this.record = record;}public int getRecord() {return record;}public void setRecord(int record) {this.record = record;}public Node getNextNode() {return nextNode;}public void setNextNode(Node nextNode) {this.nextNode = nextNode;}}/** * @author luochengcheng *兩種方式實現單鏈表的反轉(遞迴、普通) *新手強烈建議旁邊拿著紙和筆跟著代碼畫圖(便於理解) */public class ReverseSingleList {/** * 遞迴,在反轉當前節點之前先反轉後續節點 */public static Node reverse(Node head) {if (null == head || null == head.getNextNode()) {return head;}Node reversedHead = reverse(head.getNextNode());head.getNextNode().setNextNode(head);head.setNextNode(null);return reversedHead;}/** * 遍曆,將當前節點的下一個節點緩衝後更改當前節點指標 * */public static Node reverse2(Node head) {if (null == head) {return head;}Node pre = head;Node cur = head.getNextNode();Node next;while (null != cur) {next = cur.getNextNode();cur.setNextNode(pre);pre = cur;cur = next;}//將原鏈表的前端節點的下一個節點置為null,再將反轉後的前端節點賦給head head.setNextNode(null);head = pre;return head;}public static void main(String[] args) {Node head = new Node(0);Node tmp = null;Node cur = null;// 構造一個長度為10的鏈表,儲存前端節點對象head for (int i = 1; i < 10; i++) {tmp = new Node(i);if (1 == i) {head.setNextNode(tmp);} else {cur.setNextNode(tmp);}cur = tmp;}//列印反轉前的鏈表Node h = head;while (null != h) {System.out.print(h.getRecord() + " ");h = h.getNextNode();}//調用反轉方法head = reverse2(head);System.out.println("\n**************************");//列印反轉後的結果while (null != head) {System.out.print(head.getRecord() + " ");head = head.getNextNode();}}}
Java反轉單鏈表(code)