[Notes for brushing questions] Reversing the linked list - head insertion method/stack implementation
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) {
ListNode temp = 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;
}
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;
}