题解 | #反转链表#
反转链表
https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
视频讲解
B站视频合集:https://www.bilibili.com/video/BV1ua41197Dh
代码部分
解法一
public ListNode reverseList(ListNode head) {
Stack<ListNode> stack = new Stack<>();
//把链表节点全部摘掉放到栈中
while (head != null) {
stack.push(head);
head = head.next;
}
if (stack.isEmpty())
return null;
ListNode newHead = stack.pop();
ListNode cur = newHead;
//栈中的结点全部出栈,然后重新连成一个新的链表
while (!stack.isEmpty()) {
ListNode next = stack.pop();
cur.next = next;
cur = next;
}
//最后一个结点就是反转前的头结点,一定要让他的next
//等于空,否则会构成环
cur.next = null;
return newHead;
}
解法二
public ListNode reverseList(ListNode head) {
//新链表
ListNode newHead = null;
while (head != null) {
//先保存访问的节点的下一个节点,保存起来
//留着下一步访问的
ListNode temp = head.next;
//每次访问的原链表节点都会成为新链表的头结点,
//其实就是把新链表挂到访问的原链表节点的
//后面就行了
head.next = newHead;
//更新新链表
newHead = head;
//重新赋值,继续访问
head = temp;
}
//返回新链表
return newHead;
}
解法三
public ListNode reverseList(ListNode head) {
// 边界条件判断
if (head == null || head.next == null)
return head;
// 反转当前节点之后的所有节点
ListNode reverse = reverseList(head.next);
head.next.next = head;
// head这时变成反转之后之后的尾节点
head.next = null;
return reverse;
}
解法四
public ListNode reverseList(ListNode head) {
return reverseListInt(head, null);
}
private ListNode reverseListInt(ListNode head, ListNode newHead) {
if (head == null)
return newHead;
ListNode next = head.next;
head.next = newHead;
return reverseListInt(next, head);
}
#数据结构编程链表#