java 双向链表:实现 Java 双向链表的优势与挑战

Java双向链表是一种特殊的链表,它允许在链表中从前向后和从后向前遍历。它由一系列节点组成,每个节点都有一个引用,它指向前一个节点和后一个节点。

Java双向链表是一种特殊的链表,它允许在链表中从前向后和从后向前遍历。它由一系列节点组成,每个节点都有一个引用,它指向前一个节点和后一个节点。

Java双向链表是一种特殊的链表,它允许在链表中从前向后和从后向前遍历。它由一系列节点组成,每个节点都有一个引用,它指向前一个节点和后一个节点。

双向链表的优点是它允许从头到尾和从尾到头遍历,这使得它比单向链表更加高效。

是一个简单的双向链表的Java代码示例:

public class DoublyLinkedList {

Node head;

// Node inner class

class Node {

int data;

Node prev;

Node next;

Node(int d) { data = d; }

}

// Adding a node at the front of the list

public void push(int new_data)

{

/* 1. allocate node

* 2. put in the data */

Node new_Node = new Node(new_data);

/* 3. Make next of new node as head and previous as NULL */

new_Node.next = head;

new_Node.prev = null;

/* 4. change prev of head node to new node */

if (head != null)

head.prev = new_Node;

/* 5. move the head to point to the new node */

head = new_Node;

}

// This function prints contents of linked list starting from the given node

public void printList(Node node)

{

Node last = null;

System.out.println("Traversal in forward Direction");

while (node != null) {

System.out.print(node.data + " ");

last = node;

node = node.next;

}

System.out.println();

System.out.println("Traversal in reverse direction");

while (last != null) {

System.out.print(last.data + " ");

last = last.prev;

}

}

// Driver program to test above functions

public static void main(String[] args)

{

/* Start with the empty list */

DoublyLinkedList dll = new DoublyLinkedList();

// Insert 6. So linked list becomes 6->NULL

dll.push(6);

// Insert 7 at the beginning. So linked list becomes 7->6->NULL

dll.push(7);

// Insert 1 at the beginning. So linked list becomes 1->7->6->NULL

dll.push(1);

// Insert 4 at the end. So linked list becomes 1->7->6->4->NULL

dll.append(4);

// Insert 8, after 7. So linked list becomes 1->7->8->6->4->NULL

dll.insertAfter(dll.head.next, 8);

System.out.println("Created DLL is: ");

dll.printList(dll.head);

}

}

本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处

(435)
java发音:听java的声音,感受编程的乐趣!
上一篇
java系统能下载微信么:Java系统如何安装微信?
下一篇

相关推荐

发表评论

登录 后才能评论

评论列表(40条)