Loading

LeetCode刷题笔记 -—- 206. 反转链表

206. 反转链表

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

示例 :

输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]

 

方法1.迭代:

定义三个指针,然后进行迭代,从而改变next指向。

 struct ListNode {
     int val;
     struct ListNode *next;
};

struct ListNode* reverseList(struct ListNode* head){
   struct ListNode * cur = head; 
   struct ListNode * las = NULL; 
   while(cur){
      struct ListNode * nextTemp  = cur.next;  
      cur.next = las;  
      las = cur;
      cur = nextTemp;
   }
}

方法2.递归

 使用递归解题,需要以下条件:

1.大问题拆成两个子问题

2.子问题与大问题的求解方式一样

3.存在最小子问题

此题就是将链表拆成head和子链表两部分,然后重复拆分,然后使head.next.next = head,head.next = null;

struct ListNode* reverseList(struct ListNode* head) {
    if (head == NULL || head->next == NULL) {
        return head;
    }
    struct ListNode* newHead = reverseList(head->next);
    head->next->next = head;
    head->next = NULL;
    return newHead;
}

 

posted @ 2021-10-05 22:12  StormArcita  阅读(77)  评论(0)    收藏  举报