java翻轉連結串列
阿新 • • 發佈:2019-01-11
翻轉連結串列:
需要經過一下步驟:
第一步:定義Node類
第二步:構造出一個鏈式表;
第三部:寫一個翻轉連結串列的函式:
第四部,在主函式中依次呼叫構建連結串列、翻轉連結串列
具體函式如下:
package cetcocean;/**
* @description:
* @author: fangchangtan
* @create: 2019-01-10 15:01
*/
import java.util.Scanner;
/**
* @description:
* @author: fangchangtan
* @create: 2019-01-10 15:01
* */
public class Square {
public static void main(String[] args) {
//構造生成連結串列:並拿到頭結點
Node head = ListNode.getSingleList();
ListNode.printList(head);
Node resultNode = reverseList(head);
ListNode.printList(resultNode);
}
public static Node reverseList (Node head) {
Node resultNode = null;
Node now = head;
while (now != null) {
Node next = now.next;
now.next = resultNode;
resultNode = now;
now = next;
}
return resultNode;
}
}
/*
定義node節點的俄資料結構
*/
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
}
}
/*
自定義ListNode:連結串列
*/
class ListNode {
public static Node getSingleList(){
Node head = new Node(4);
Node node2 = new Node(3);
Node node3 = new Node(2);
Node node4 = new Node(1);
head.next = node2;
node2.next = node3;
node3.next = node4;
return head;
}
public static void printList(Node node) {
System.out.println("List is : ");
while (node != null) {
System.out.print(node.data +",");
node = node.next;
}
}
}
最終結果: