

LeetCode 上第 206 号问题:Reverse Linked List
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
设置三个节点pre、cur、next
cur节点是否为NULL,如果是,则结束循环,获得结果cur节点不是为NULL,则先设置临时变量next为cur的下一个节点cur的下一个节点变成指向pre,而后pre移动cur,cur移动到next动画演示 GIF 有点大,请稍微等待一下加载显示^_^

// 206. Reverse Linked List // https://leetcode.com/problems/reverse-linked-list/description/ // 时间复杂度: O(n) // 空间复杂度: O(1) class Solution { public: ListNode* reverseList(ListNode* head) { ListNode* pre = NULL; ListNode* cur = head; while(cur != NULL){ ListNode* next = cur->next; cur->next = pre; pre = cur; cur = next; } return pre; } }; // 206. Reverse Linked List // https://leetcode.com/problems/reverse-linked-list/description/ // // 递归的方式反转链表 // 时间复杂度: O(n) // 空间复杂度: O(1) class Solution { public: ListNode* reverseList(ListNode* head) { // 递归终止条件 if(head == NULL || head->next == NULL) return head; ListNode* rhead = reverseList(head->next); // head->next 此刻指向 head 后面的链表的尾节点 // head->next->next = head 把 head 节点放在了尾部 head->next->next = head; head->next = NULL; return rhead; } }; 
我们会在公众号(菠了个菜)上每天早上 8 点 30 分准时推送一条 LeetCode 上的算法题目,并给出该题目的动画解析以及参考答案,每篇文章阅读时长为五分钟左右。
1 yifanes 2018-11-03 10:10:11 +08:00 via iPhone 希望可以坚持,或者至少 200 题+ |
2 CoderOnePolo OP @yifanes 会坚持住的,目前已经写了 40+ |