LeetCode 206-Reverse Linked List (reverse a singly linked list)

Title:

Reverse a singly linked list.

Example:

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

Advanced:
You can reverse the linked list iteratively or recursively. Can you solve this problem in two ways?

analyze:

head plug.

Iterate:

The newhead is the head of the new chain,
1. Each time the head of the chain is taken out from the head of the original chain, it is named now (the element to be inserted),
2. The original chain is updated
3. Now is inserted into the head of the newhead

Recursion:
The code is short but ingenious, see this link:
https://blog.csdn.net/puqutogether/article/details/45487797

Code:

Iterate:

class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode newhead=null;
        ListNode now;
        while(head!=null){
            now=head;         //取头
            head=head.next;   //更新原链头
            now.next=newhead; //插入新链
            newhead=now;      //更新新链头
        }
        return newhead;
    }
}

Recursive:

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325167472&siteId=291194637