[Notes for brushing questions] Reversing the linked list - head insertion method/stack implementation

[Notes for brushing questions] Reversing the linked list - head insertion method/stack implementation

insert image description here

Solution one: head plugging method

Idea and code:

 * 1、创建一个newhead=null,即最终反转后的链表的头结点
 * 2、循环遍历当前的链表的head,创建temp记录当前head的next,然后将head的next指向新的头newhead,并将newhead=head完成newhead迁移为新的头
 * 最后将head更新为之前head的next即head=temp,进而完成遍历
 * 3、输出newhead
public ListNode Reverse(ListNode head) {
    
    
        ListNode newhead = null;
        while (head != null) {
    
    
            //记录当前head的next节点
            ListNode temp = head.next;
            //因为是头插法(head.next)
            head.next = newhead;
            newhead = head;
            head = temp;
        }
        return newhead;
    }

Solution 2: Implement using a stack (Stack)

ideas and code

 * 1、创建Stack栈,遍历链表并将链表各个元素并入栈
 * 2、判断插入元素后的栈是否为空,是则返回null
 * 3、设定result为输出链表的头节点,遍历栈中的元素添加到result新链表中(建立新的链表)
public ListNode reverseByStack(ListNode head) {
    
    
        Stack<ListNode> stack = new Stack<>();
        //遍历链表并将链表元素入栈
        while (head != null) {
    
    
            stack.push(head);
            head = head.next;
        }
        //判断栈是否为空
        if (stack.isEmpty()) {
    
    
            return null;
        }
        //设定result作为输出的头节点(以result为头节点建立新链表)
        ListNode result = stack.pop();
        ListNode node = result;
        while (!stack.isEmpty()) {
    
    
            ListNode temp = stack.pop();
            //建链表
            node.next = temp;
            node = node.next;
        }
        node.next = null;
        return result;
    }

Guess you like

Origin blog.csdn.net/weixin_43950588/article/details/131308705