Leetcode[206] 反转链表

题目描述

反转一个单链表
示例:

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

题解思路

迭代思路
  1. 边界条件:当只有零个或一个节点时,返回头节点指针即可;
  2. 建立以第一个节点新的链表头,新表头 next 为 NULL;
  3. 从第二个节点遍历链表,从头部插入新的链表,临时指针 temp 存放 next 节点指针;
递归思路
  1. 终止条件:当前节点或者下一个节点为NULL;
  2. 在函数内部递归改变节点指向:head -> next -> next = head;

AC代码

迭代算法:

struct ListNode* reverseList(struct ListNode* head){
    // 边界条件,当 head == NULL 或 head -> next == NULL, return head
    if(head == NULL || head -> next == NULL) {
        return head;
    }
    struct ListNode *p = head -> next;
    struct ListNode *newhead = head;
    newhead -> next = NULL;
    struct ListNode *temp = NULL;
    while(p != NULL) {
        temp = p -> next;
        p -> next = newhead;
        newhead = p;
        p = temp;
    }
    return newhead;
}

递归算法:

struct ListNode* reverseList(struct ListNode* head){
    if(head == NULL || head -> next == NULL) {
        return head;
    }
    struct ListNode *p = reverseList(head -> next);
    head -> next -> next = head;
    head -> next = NULL;
    return p;
}
发布了52 篇原创文章 · 获赞 81 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/xiaoma_2018/article/details/104195762