Sword finger - reverse linked list - stack + recursion

Question description

Input a linked list, reverse the linked list, and output the header of the new linked list.

Ideas

1. Stack.
Push the linked list nodes onto the stack one by one, and then pop them off the stack one by one. When popping them off the stack, string the popped nodes into a new linked list.

2. Recursion.
The termination condition is that the current node or next node == null
is inside the function, changing the direction of the node, that is, the next node of head points to the head recursive function.

code

1. Stack

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 node = stack.pop();
    ListNode dummy = node; // 保存头结点***
    //栈中的结点全部出栈,然后重新连成一个新的链表
    while (!stack.isEmpty()) {
    
    
        ListNode tempNode = stack.pop();
        node.next = tempNode;
        node = node.next;
    }
    //最后一个结点就是反转前的头结点,一定要让他的next
    //等于空,否则会构成环***
    node.next = null;
    return dummy;
}

2. Recursion.

class Solution {
    
    
	public ListNode reverseList(ListNode head) {
    
    
		//递归终止条件是当前为空,或者下一个节点为空
		if(head==null || head.next==null) {
    
    
			return head;
		}
		//这里的cur就是最后一个节点
		ListNode cur = reverseList(head.next);
		//如果链表是 1->2->3->4->5,那么此时的cur就是5
		//而head是4,head的下一个是5,下下一个是空
		//所以head.next.next 就是5->4
		head.next.next = head;
		//防止链表循环,需要将head.next设置为空
		head.next = null;
		//每层递归函数都返回cur,也就是最后一个节点
		return cur;
	}
}

Stack is easy to understand.
If you can’t understand recursion, just memorize it.

Guess you like

Origin blog.csdn.net/qq_32301683/article/details/108462773