用Java实现反转链表起⽹络
时间: 2023-07-11 10:44:03 浏览: 84
JAVA双向链表反转实现
反转链表是一个常见的面试题,以下是用Java实现反转链表的代码:
```java
class Node {
int val;
Node next;
public Node(int val) {
this.val = val;
this.next = null;
}
}
class ReverseLinkedList {
Node head;
public ReverseLinkedList() {
head = null;
}
public void insert(int val) {
if (head == null) {
head = new Node(val);
return;
}
Node curr = head;
while (curr.next != null) {
curr = curr.next;
}
curr.next = new Node(val);
}
public void reverse() {
Node prev = null;
Node curr = head;
Node next = null;
while (curr != null) {
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
head = prev;
}
public void printList() {
Node curr = head;
while (curr != null) {
System.out.print(curr.val + " ");
curr = curr.next;
}
System.out.println();
}
}
```
这里定义了一个Node类和ReverseLinkedList类,Node类表示链表中的节点,ReverseLinkedList类表示链表。insert方法用于插入节点,reverse方法用于反转链表,printList方法用于打印链表。reverse方法里使用了三个指针prev、curr、next,分别表示前一个节点、当前节点和下一个节点,通过改变节点之间的链接关系,实现了反转链表的功能。
阅读全文