2013-08-15 3 views
1

Я внимательно следил за видеороликами YouTube, чтобы понять связанные списки до того, как начнутся уроки осеннего урока, и я не знаю, как продолжить повторение в следующем связанном списке. Класс «node» - из серии видео (тот же автор), но «основной» метод был написан мной. Могу ли я приближались к конструкции связанного списка в нелогичным образом (при условии, конечно, один делает не желание использовать предопределенный класс LinkedList, так как профессор будет ожидать каждого из нас, чтобы написать собственную реализацию) ?:Итерация по связанному списку в Java?

class Node 
{ 
    private String data; 
    private Node next; 

    public Node(String data, Node next) 
    { 
     this.data = data; 
     this.next = next; 
    } 

    public String getData() 
    { 
     return data; 
    } 

    public Node getNext() 
    { 
     return next; 
    } 

    public void setData(String d) 
    { 
     data = d; 
    } 

    public void setNext(Node n) 
    { 
     next = n; 
    } 

    public static String getThird(Node list) 
    { 
     return list.getNext().getNext().getData(); 
    } 

    public static void insertSecond(Node list, String s) 
    { 
     Node temp = new Node(s, list.getNext()); 
     list.setNext(temp); 
    } 

    public static int size(Node list) 
    { 
     int count = 0; 

     while (list != null) 
     { 
      count++; 
      list = list.getNext(); 
     } 

     return count; 
    } 
} 

public class LL2 
{ 
    public static void main(String[] args) 
    { 
     Node n4 = new Node("Tom", null); 
     Node n3 = new Node("Caitlin", n4); 
     Node n2 = new Node("Bob", n3); 
     Node n1 = new Node("Janet", n2); 

    } 
} 

Спасибо за помощь,

Кейтлин

+2

Вы только узлы здесь. Вы должны реализовать список, который содержит первый и последний узел, а также размер. Вам нужны, по крайней мере, следующие классы: Node; NodeList. –

+0

Вот только класс Node, где класс List? вы смешиваете их обоих, я думаю, вы не поняли правильно связанный список. –

+0

Посмотрите здесь, как реализовать его с помощью Node и NodeList: http://en.wikipedia.org/wiki/Linked_list#Linked_list_operations –

ответ

3

Есть некоторые недостатки в связанном списке, как указано на некоторые из других комментариев. Но у вас есть хороший старт, который захватывает идею связанного списка и выглядит функционально. Для того, чтобы ответить на базовый вопрос о том, как цикл по этой конкретной РЕАЛИЗАЦИЯ связанного списка вы делаете это

Node currentNode = n1; // start at your first node 
while(currentNode != null) { 
    // do logic, for now lets print the value of the node 
    System.out.println(currentNode.getData()); 
    // proceed to get the next node in the chain and continue on our loop 
    currentNode = currentNode.getNext(); 
} 
1

Может быть, это будет полезно:

static void iterate(Node head) { 
    Node current = head; 
    while (current != null) { 
     System.out.println(current.getData()); 
     current = current.getNext(); 
    } 
} 

// or through recursion 
static void iterateRecursive(Node head) { 
    if (head != null) { 
     System.out.println(head.getData()); 
     iterateRecursive(head.getNext()); 
    } 
} 
0
class List {   
    Item head; 

    class Item {   
     String value; Item next; 
     Item (String s) { value = s; next = head; head = this; } 
    } 

    void print() { 
     for(Item cursor = head; cursor != null; cursor = cursor.next) 
      System.out.println (cursor.value); 
    } 

    List() { 
     Item one = new Item ("one"); 
     Item two = new Item ("three"); 
     Item three = new Item ("Two"); 
     Item four = new Item ("four"); 
    } 
} 

public class HomeWork { 
    public static void main(String[] none) { new List().print(); } 
} 

Успехов !!

0

У вас может быть связанный список. Класс DS реализует интерфейс Iterable и переопределяет методы hasNext(), next() или создает для вас внутренний класс. Посмотрите на ниже реализации:

public class SinglyLinkedList<T>{ 
private Node<T> head; 
public SinglyLinkedList(){ 
    head = null; 
} 

public void addFirst(T item){ 
    head = new Node<T>(item, head); 
} 
public void addLast(T item){ 
    if(head == null){ 
     addFirst(item); 
    } 
    else{ 
     Node<T> temp = head; 
     while(temp.next != null){ 
      temp = temp.next; 
     } 
     temp.next = new Node<T>(item, null); 
    } 
} 

private static class Node<T>{ 
    private T data; 
    private Node<T> next; 
    public Node(T data, Node<T> next){ 
     this.data = data; 
     this.next = next; 
    } 
} 
private class LinkedListIterator implements Iterator<T>{ 
    private Node<T> nextNode; 
    public LinkedListIterator(){ 
     nextNode = head; 
    } 

    @Override 
    public boolean hasNext() { 
     return (nextNode.next != null); 
    } 

    @Override 
    public T next() { 
     if(!hasNext()) throw new NoSuchElementException(); 
     T result = nextNode.data; 
     nextNode = nextNode.next; 
     return result; 
    } 

} 

}

Смежные вопросы