1. 程式人生 > 實用技巧 >java實現連結串列的反轉

java實現連結串列的反轉

摘要

最近筆試一家公司,其中一道題目:如何用java實現連結串列的反轉,如:{a,b,c,d}反轉後變為:{d,c,b,a},只能操作一個連結串列。 當時不曉得怎麼做。還以為使用棧來實現。圖樣圖森破。
public class Node

{


  private Node next;
  private String value;
 
  public Node(String value){
    this.value=value;
  }
  public Node getNext() {
    return next;
  }
  public void setNext(Node next) {
    
this.next = next; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public static void main(String[] args) { Node head=new Node("a"); Node node1=new Node("b"); Node node2=new Node("c"); Node node3=new Node("d");
//初始化連結串列 head.setNext(node1); node1.setNext(node2); node2.setNext(node3); System.out.println("列印連結串列反轉前:"); reverse(head); //設定head的下一個元素為null,注意:此時head已經成為連結串列尾部元素。 head.next=null; while(node3!=null){ System.out.print(node3.getValue()); node3=node3.getNext();
if(node3!=null){ System.out.print("->"); } } } /** * 利用迭代迴圈到連結串列最後一個元素,然後利用nextNode.setNext(head)把最後一個元素變為 * 第一個元素。 * * @param head */ public static void reverse(Node head){ if(head!=null){ Node nextNode=head.getNext(); if(nextNode!=null){ reverse(nextNode); nextNode.setNext(head); } } } }