题海拾贝:力扣 反转链表
Hello大家好!很高兴我们又见面啦!给生活添点passion,开始今天的编程之路!
我的博客:<但凡.
我的专栏:《编程之路》、《数据结构与算法之美》、《题海拾贝》
欢迎点赞,关注!
1、题目
2、题解
思路一(最优解):
/**
* 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;
}
else
{
struct ListNode*n1=head;
struct ListNode*n2=head->next;
struct ListNode*n3=n2->next;
n1->next=NULL;
while(n3!=NULL)
{
n2->next=n1;
n1=n2;n2=n3;n3=n3->next;
}
n2->next=n1;
return n2;
}
}
思路二(空间换时间):
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* reverseList(struct ListNode* head) {
if (head == NULL || head->next == NULL)
{
return head;
}
struct ListNode* newhead = head;
struct ListNode* cur = head->next;
head->next = NULL;//注意,易错点,不写会造成死循环
while (cur)
{
//错误示范
//struct ListNode* pcur = cur;
把pcur头插到新链表上
//pcur->next = newhead;
//newhead = pcur;
//方法一
/* struct ListNode* pcur = (struct ListNode*)malloc(sizeof(struct ListNode));
pcur->val = cur->val;
pcur->next = newhead;
newhead = pcur;
cur = cur->next;*/
//方法二
struct ListNode* pcur = cur;
cur = cur->next;
pcur->next = newhead;
newhead = pcur;
}
return newhead;
}
好了,今天不的内容就分享到这,我们下期再见!