java逆转单链表_逆转单向链表看这一篇就够了【JAVA】

逆转单向链表

逆转前: 1 -> 2 -> 3 -> 4 -> 5 -> null

逆转后: 5 -> 4 -> 3 -> 2 -> 1 -> null

72f805a3182ed04ac5c51699b0f00c2e.png

public Node reverse(Node head) {

if (head == null || head.next == null) {

return head;

}

// 取前面节点

Node pre = head;

// 取后面节点

Node cur = head.next;

// 临时节点

Node temp = null;

while (cur != null) {

// 1. 保存后节点的指向节点 因为要替换后节点的指向节点为他的前节点

temp = cur.next;

// 2. 把后节点的指向的节点替换成前节点

cur.next = pre;

// 下一轮要替换的前节点和后节点

// 第一次 pre = 1 cur =2 || 那第二次 就得 pre = 2 cur = 3

pre = cur;

cur = temp;

}

// 在上述过程中未替换首节点的指向节点 这里首节点将成为尾节点 所以指向null

head.next = null;

// 因为循环的条件是cur是否为null 如果cur为null 那 pre将是原来链表的尾节点

// 就是逆转后的首节点

return cur;

}

public Node recursionNode(Node head) {

if (head == null || head.next == null) {

return head;

}

// head 1 2 3 4

Node node = reverseNode(head.next);

// 展示顺序 head 4 3 2 1

// 第一轮:

// 当前指向顺序 4 -> 5

head.next.next = head; // 变成了 5 -> 4 但是4的指针仍然指向5 也就是双向的

// 所以 4 -> null 变成单向

head.next = null;

// node是最后一个元素 5 也就是逆转后的 第一个元素

return node;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值