Java创建一个单链表
时间: 2023-10-19 09:08:28 浏览: 44
好的,让我为您解答Java创建单链表的问题。首先,需要先定义一个节点类,如下所示:
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
然后,可以通过循环来创建单链表:
ListNode head = new ListNode(0);
ListNode curr = head;
for(int i=1; i<=n; i++) {
ListNode temp = new ListNode(i);
curr.next = temp;
curr = curr.next;
}
其中,n表示链表的长度。希望这个答案对您有所帮助。
相关问题
用JAVA生成一个单链表并解释
单链表是一种常见的数据结构,它由一系列结点组成,每个结点包含两部分:数据域和指针域。其中数据域用于存储数据,指针域用于指向下一个结点。
下面是用JAVA生成单链表的代码示例:
```
class Node {
int data; // 数据域
Node next; // 指针域
public Node(int data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
Node head;
public LinkedList() {
this.head = null;
}
public void add(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
return;
}
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
}
public void display() {
Node current = head;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
}
}
public class Main {
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.add(1);
list.add(2);
list.add(3);
list.display();
}
}
```
以上代码首先定义了一个结点类Node,包含数据域和指针域,然后定义了一个单链表类LinkedList,包含头结点head和添加结点的方法add以及打印链表的方法display。在主函数中,创建一个链表实例list,添加数据1、2、3,最后打印链表。
希望以上解释对您有所帮助!
java定义一个循环单链表
以下是Java定义一个循环单链表的示例代码:
```java
public class CircularLinkedList {
private Node head;
private Node tail;
private int size;
private class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
}
}
public CircularLinkedList() {
head = null;
tail = null;
size = 0;
}
public boolean isEmpty() {
return size == 0;
}
public int getSize() {
return size;
}
public void add(int data) {
Node newNode = new Node(data);
if (isEmpty()) {
head = newNode;
tail = newNode;
} else {
tail.next = newNode;
tail = newNode;
}
tail.next = head; // make the list circular
size++;
}
public void display() {
if (isEmpty()) {
System.out.println("List is empty");
} else {
Node current = head;
do {
System.out.print(current.data + " ");
current = current.next;
} while (current != head);
System.out.println();
}
}
}
```
在上述代码中,我们定义了一个内部类 `Node` 表示链表中的节点,其中包含一个 `int` 类型的数据域和一个指向下一个节点的 `next` 引用。`CircularLinkedList` 类包含了一个头节点 `head`、一个尾节点 `tail` 和链表的大小 `size`,并提供了一些常用的方法,如 `isEmpty()`、`getSize()`、`add()` 和 `display()` 等。
在 `add()` 方法中,我们首先创建一个新节点 `newNode`,然后判断链表是否为空。如果为空,将 `newNode` 赋给 `head` 和 `tail`,否则将 `newNode` 添加到链表的尾部。最后,将 `tail` 的 `next` 引用指向 `head`,使链表变为循环链表。
在 `display()` 方法中,我们使用 `do-while` 循环遍历整个链表,并输出每个节点的数据域。由于这是一个循环链表,所以当 `current` 指向 `head` 时,我们就可以退出循环了。