Algorithm review - Sword pointing at Offer and reverse linked list

The sword points to Offer and reverses the linked list

Question:
Define a function that inputs the head node of a linked list, reverses the linked list and outputs the head node of the reversed linked list.
Example:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

Solution 1: Iterative method
1. First, we need to point the pointer in the opposite direction and output the result in the opposite direction. So the first thing is to make the node 1 point to null, and 2 point to
1. After 2 and 2 point to 1, remember the next 3, otherwise it will not be found later.
3. Define a prev and let it point to null.
4. Define a next and let it retain the subsequent node address to prevent it from being found.
5. Define a current variable curr to point to the previous node, such as 2 pointing to 1.

Code:

class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode pre=null,next;
        ListNode cur=head;
        while(cur!=null){
            next=cur.next;
            cur.next=pre;
            pre=cur;
            cur=next;
        }
        return pre;
    }
}

Solution 2: Recursive method
The idea of ​​recursion is to call a repetitive process repeatedly to complete the entire code.
We can first understand that the next node of 1 is 2, and the next node of 2 is 3. If we want to output the node in reverse, we need 2 to point to 1 and 1 to null, then it is the next node of the next node of 1 (2) The next node pointing to 1,1 points to null. That is, head.next.next=head; head.next=null;
then such pointing is continued between the two nodes to complete the reverse output.
Code:

class Solution {
    public ListNode reverseList(ListNode head) {
        if(head==null||head.next==null){
            return head;
        }
        ListNode node=reverseList(head.next);
        head.next.next=head;
        head.next=null;
        return node;
    }
}

Insert image description here

Guess you like

Origin blog.csdn.net/weixin_45667289/article/details/124672510