第一种方法:使用stack
这种方法需要额外空间,创建栈,然后将链表遍历存入栈,接着弹出栈,重新连接链表,而且需要两次遍历。这种方法没什么技术含量,但是架不住思想很简单。。。所以如果笔试碰到,可以直接写,如果是面试的话只给出这种方法我觉得基本上就凉了。。。
// 使用Stack反转链表
private static Node reverseList1(Node head) {
if (head == null) return null;
Stack<Node> stack = new Stack<>();
Node cur = head;
while ( cur != null ) {
stack.push(new Node(cur.value));
cur = cur.next;
}
cur = stack.pop();
Node newHead = cur;
while ( !stack.isEmpty() ) {
cur.next = stack.pop();
cur = cur.next;
}
return newHead;
}
第二种方法:在遍历的过程中从头开始反转(非递归)
- 首先使用一个变量保存当前节点的下一个节点。
- 接着用另外一个变量保存当前节点的前一个节点,将当前节点的next指向前一个节点。
- 将当前节点和当前节点的前一个节点后移。
// 非递归反转链表
private static Node reverseList2(Node head) {
Node pre = null;
Node next = null;
while ( head != null ) {
next = head.next;//next保存head下一个节点
head.next = pre;//将当前节点next指向前一个节点,实现反转
pre = head;//将当前节点的前节点后移
head = next;//将当前节点后移
}
return pre;
}
第三种方法:从尾到头进行反转(递归)
这种方法的思想是通过递归的方法实现从尾到头的遍历,我对这种方法的理解不是很好,所以就不误导别人了,这里有讲解,可以参考这篇学习其思想链表翻转的图文讲解(递归与迭代两种实现)
// 递归反转链表
private static Node reverseList3(Node head) {
if(head==null||head.next ==null)
return head;
Node next = head.next;
Node prev = reverseList3(next);
head.next.next = head;
head.next = null;
return prev;
}
完整测试代码:反转链表