2-4反轉鏈表

題目描述

  • 反轉單鏈表

解題方法1

  • 遍歷鏈表,利用頭插法將節點依次插入到頭節點之後。
public class Test {
    public static void main(String[] args) throws Exception {
       int[] arr = {10,20,30,40,50};
       Node head = create(arr);
        reverse(head);
       for(Node p = head.next;p!=null;p=p.next){
           System.out.println(p.val);
       }
    }
    //反轉鏈表
    public static Node reverse(Node head){
        if(head==null || head.next==null){
            return head;
        }
        Node p = head.next;
        head.next = null;
        while(p!=null){
            Node temp = p.next;
            p.next = head.next;
            head.next = p;
            p=temp;
        }
        return head;
    }
    public static Node create(int[] arr){
        Node head = new Node(0); //頭節點
        Node newnode = null; //指向新節點
        Node tail = head; //指向鏈表尾節點
        for(int a:arr){
            newnode = new Node(a);
            newnode.next = tail.next;
            tail.next = newnode;
            tail = newnode;
        }
        return head;
    }
}
class Node{
    int val;
    Node next;
    Node(int val){
        this.val = val;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章