java链表的代码实现
时间: 2023-04-03 21:00:27 浏览: 79
可以使用以下代码实现一个简单的单向链表:
```
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Node* head = NULL;
void insert(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = head;
head = newNode;
}
void printList() {
struct Node* current = head;
printf("List: ");
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
insert(1);
insert(2);
insert(3);
printList();
return ;
}
```
相关问题
用java代码实现链表
以下用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 insert(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
} else {
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
}
System.out.println(data + " 插入成功!");
}
// 遍历链表并打印节点值
public void display() {
if (head == null) {
System.out.println("链表为空!");
return;
}
Node current = head;
System.out.print("链表内容: ");
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}
}
// 测试链表功能
public class Main {
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.insert(5);
list.insert(10);
list.insert(15);
list.display();
}
}
```
运行上述代码,将输出:
```
5 插入成功!
10 插入成功!
15 插入成功!
链表内容: 5 10 15
```
这个示例展示了一个简单的链表实现,其中包括节点插入和链表遍历功能。你可以根据需要添加其他操作,如删除节点、查找节点等。
Java代码实现反转链表
以下是Java代码实现反转链表的示例:
```java
private static Node reverseLinkedList(Node head) {
Node prev = null;
Node current = head;
Node next = null;
while (current != null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
return prev;
}
```
这段代码中,我们使用了三个指针prev、current和next来完成链表的反转操作。prev指向当前节点的前一个节点,current指向当前节点,next指向当前节点的下一个节点。在每一次循环中,我们将current的next指针指向prev,然后更新prev、current和next的指向,直到遍历完整个链表。最后,返回反转后的链表的头节点。
你可以使用这个方法来反转一个链表,并通过遍历链表的方法验证反转的准确性。例如,你可以使用上面提到的showLink方法来打印反转后的链表。
希望这个示例能够帮助到你!