问题:
反转一个单链表。
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
解题思路:此题可以使用递归思想求解。首先还是写出递归终止条件。然后假设只差最后一步没有反转,如例子:1->2<-3<-4<-5,我们需要做的就只剩下将2指向1就可以了。
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode newListNode = reverseList(head.next);
head.next.next = head;
head.next = null;
return newListNode;
}
}
遍历解法:一次循环,需要三个指针,分别指向当前节点,它的前节点和后节点。记录好当前节点的后一个节点后,开始反转,最后进行平移。这里需要注意的是将pre前节点初始设置成null,这样反转后最后一个节点就是指向null的。
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode prev = null;
ListNode current = head;
while (current != null) {
ListNode next = current.next;
current.next = prev;
prev = current;
current = next;
}
return prev;
}
}