原题地址
剑指 Offer 24. 反转链表
题目描述
题目思路
方法一:辅助栈
利用栈先入后出的特点,依次将链表元素入栈,再从中弹出连接为新链表。
方法二:递归法
利用递归思想,先访问至链表末端,从末端开始往前连接。
方法三:迭代法
代码实现
使用到的方法
pop():移除堆栈顶部的对象,并作为此函数的值返回该对象。 push():把项压入堆栈顶部。 empty():判断是否为空栈。
辅助栈法
class Solution {
private Stack < ListNode > stack = new Stack < ListNode > ( ) ;
private ListNode virNode = new ListNode ( ) ;
private ListNode curNode = new ListNode ( ) ;
public ListNode reverseList ( ListNode head) {
if ( head == null ) {
return null ;
}
while ( head != null ) {
stack. push ( head) ;
head = head. next;
}
virNode. next = stack. pop ( ) ;
curNode = virNode. next;
while ( ! stack. empty ( ) ) {
curNode. next = stack. pop ( ) ;
curNode = curNode. next;
}
curNode. next = null ;
return virNode. next;
}
}
递归法
class Solution {
ListNode virNode = new ListNode ( ) ;
public ListNode reverseList ( ListNode head) {
recur ( head, null ) ;
return virNode. next;
}
void recur ( ListNode curNode, ListNode preNode) {
if ( curNode == null ) {
virNode. next = preNode;
return ;
}
recur ( curNode. next, curNode) ;
curNode. next = preNode;
}
}
迭代法
class Solution {
ListNode pre = null ;
ListNode next = null ;
public ListNode reverseList ( ListNode head) {
if ( head == null || head. next == null ) {
return head;
}
while ( head != null ) {
next = head. next;
head. next = pre;
pre = head;
head = next;
}
return pre;
}
}