2017-10-09 15 views
0

對於noob問題抱歉,但是這裏的語法有點混亂。我被要求填寫函數以將新元素插入到鏈表的前面。代碼:使用數據創建新的頭像列表

class LinkedList 
{ 
    public LinkedList() 
    { 
     this.head = null; 
    } 

    /* returns true, if the list is empty, else false */ 
    public boolean isEmpty() 
    { 
     return head == null; 
    } 

    /* returns the first element of the list, assuming that the list is not empty */ 
    public int front() 
    { 
     return head.data; 
    } 

    /* prints the list */ 
    public void print() 
    { 
     System.out.print("("); 
     for (ListNode i = head; i != null; i = i.next) 
      System.out.print(i.data + " "); 
     System.out.println(")"); 
    } 

    /* inserts x into the beginning of the list */ 
    public void insertFront (int x) 
    { 
     /* FILL HERE!!! */ 
    } 
} 

爲節點的代碼:

class ListNode 
{ 
    public ListNode() 
    { 
     this.data = 0; 
     this.next = null; 
    } 

    public int data; 
    public ListNode next; 
} 

我想我需要創建一個新的節點,指定當前頭爲未來運營商的價值,並設置相同的值到x。然後最後將節點設置爲新的頭部。

有人可以告訴我如何執行這些基本命令。

回答

1

只要聲明您的新元素爲head並讓它指向前一個頭,現在是第二個元素。

/* inserts x into the beginning of the list */ 
public void insertFront(int x) 
{ 
    // Temporarily memorize previous head 
    ListNode previousHead = this.head; 

    // Create the new head element 
    ListNode nextHead = new ListNode(); 
    nextHead.data = x; 
    // Let it point to the previous element which is now the second element 
    nextHead.next = previousHead; 

    // Update the head reference to the new head 
    this.head = nextHead; 
} 

下面是該方法的小插圖:

LinkedList structure, inserting at front

相關問題