C语言重构【206】反转链表

it2023-07-09  67

文章目录

所有题目源代码:[Git地址](https://github.com/ch98road/leetcode)题目方案:复杂度计算

所有题目源代码:Git地址

题目

反转一个单链表。 示例: 输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL 进阶: 你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

方案:

/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* reverseList(ListNode* head) { if(head==NULL) return head; ListNode *cur=NULL,*pre=head,*tmp=head->next; while(tmp!=NULL){ pre->next=cur; cur=pre; pre=tmp; tmp=tmp->next; } pre->next=cur; return pre; } };
复杂度计算
时间复杂度:O(n)空间复杂度:O(1)
最新回复(0)