代码结构
反转单链表
//单链表节点
public static class ListNode {
public int val;
public ListNode next;
public ListNode(int val) {
this.val = val;
}
public ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
//单链表反转
class _008_ListReverse {
public static ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode next = null;
//next指针用于保存head.next的值 是下一个节点
//pre指针 指向head,是前一个节点(head) 因为后面head会往下一个走
//head是当前节点
while (head != null) {
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
力扣206
解释
反转双链表
//定义双链表节点
class DoubleListNode {
int value; // 假设节点存储的是整数,你可以根据需要修改为其他类型
DoubleListNode next;
DoubleListNode last;
public DoubleListNode(int value) {
this.value = value;
this.next = null;
this.last = null;
}
}
//反转双链表
public static DoubleListNode reverseDoubleList(DoubleListNode head){
DoubleListNode pre = null;
DoubleListNode next = null;
while (head != null) {
next = head.next;
head.next = pre;
head.last = next;
pre = head ;
head = next;
}
return pre;
}
提醒自己:还是不理解就问ai。让ai解释代码。双链表还不会