反转一个链表<难度系数⭐>
【摘要】 📝 题述:给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。💨 示例1:输入:head = [1,2,3,4,5]输出:[5,4,3,2,1]💨 示例2:输入:head = [1,2]输出:[2,1]💨 示例3:输入:head = [ ]输出:[ ]🧷 平台:Visual studio 2017 && windows🔑 核心思想:思路1,调整节点指针的方向思路2,...
📝 题述:给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
💨 示例1:
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
💨 示例2:
输入:head = [1,2]
输出:[2,1]
💨 示例3:
输入:head = [ ]
输出:[ ]
🧷 平台:Visual studio 2017 && windows
🔑 核心思想:
思路1,调整节点指针的方向
思路2,头插
#include<stdio.h>
#include<stdlib.h>
typedef int SLTDataType;
struct ListNode
{
int val;
struct ListNode *next;
};
//思路1
struct ListNode* reverseList1(struct ListNode* head)
{
//空链表
if(head == NULL)
return head;
struct ListNode* n1, *n2, *n3;
n1 = NULL;
n2 = head;
n3 = head->next;
while(n2)
{
n2->next = n1;
n1 = n2;
n2 = n3;
//最后一次进来时,n3为空指针
if(n3)
n3 = n3->next;
}
return n1;
}
//思路2
struct ListNode* reverseList2(struct ListNode* head)
{
struct ListNode *newnode, *cur, *next;
newnode = NULL;
cur = head;
while(cur)
{
next = cur->next;
cur->next = newnode;
newnode = cur;
cur = next;
}
return newnode;
}
int main()
{
struct ListNode* n1 = (struct ListNode*)malloc(sizeof(struct ListNode));
n1->val = 1;
struct ListNode* n2 = (struct ListNode*)malloc(sizeof(struct ListNode));
n2->val = 2;
struct ListNode* n3 = (struct ListNode*)malloc(sizeof(struct ListNode));
n3->val = 3;
struct ListNode* n4 = (struct ListNode*)malloc(sizeof(struct ListNode));
n4->val = 4;
struct ListNode* n5 = (struct ListNode*)malloc(sizeof(struct ListNode));
n5->val = 5;
n1->next = n2;
n2->next = n3;
n3->next = n4;
n4->next = n5;
n5->next = NULL;
reverseList1(n1);
reverseList2(n1);
return 0;
}
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)