反转一个单链表。

示例:

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

使用迭代方法,代码如下:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* reverseList(struct ListNode* head){
    if (head == NULL || head->next == NULL)
        return head;
    
    struct ListNode *pre = head;
    struct ListNode *cur = head->next;
    struct ListNode *tmp = head->next->next;
    
    while(cur)
    {
        tmp = cur->next;
        cur->next = pre;
        pre = cur;
        cur = tmp;
    }
    head->next = NULL;
    
    return pre;

}

递归方法如下:

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

总结下,递归的写法,整体来看,递归可以分成两个部分,一个是,对最里层的递归进行判断,那么对于这道题,最里层的递归就是当head为空,或者head->next为空。然后写第二个部分,从最外层开始,并且假设,剩余的部分传入递归函数返回的为已经反转的链表,然后做剩余的部分。递归函数就是要注意一个头一个尾,然后中间部分由递归完成就可以了。

相关文章:

  • 2021-12-18
  • 2022-12-23
  • 2021-08-09
  • 2021-07-10
  • 2022-12-23
猜你喜欢
  • 2021-06-02
  • 2022-12-23
  • 2021-10-30
  • 2022-12-23
  • 2022-12-23
  • 2021-09-01
  • 2021-07-09
相关资源
相似解决方案