Question type: double pointer, recursion
- It can be written with double pointers, which is easier to think and simpler
- It can also be solved in a recursive way, pay attention to the way of thinking of recursive programming
topic
Define a function that takes as input the head node of a linked list, reverses the linked list and outputs the head node of the reversed linked list.
Thinking questions:
请同时实现迭代版本和递归版本。
Sample
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
java code
recursive solution
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode tail = reverseList(head.next);
head.next.next = head;
head.next = null;
return tail;
}
}
iterative solution
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode pre = head, q = head.next;
while (q != null) {
ListNode t = q.next;
q.next = pre;
pre = q;
q = t;
}
head.next = null;
return pre;
}
}