LeetCode : Reverse Linked List
题目原意:输入一条单向简单链表,将其中的元素反置,并返回。
如输入为:1->2->3->4->5->NULL
输出为: 5->4->3->2->1->NULL
把题意理解正确了,本题就不存在什么难处了。
题目原意:输入一条单向简单链表,将其中的元素反置,并返回。
如输入为:1->2->3->4->5->NULL
输出为: 5->4->3->2->1->NULL
把题意理解正确了,本题就不存在什么难处了。
代码如下(leetCode 测得运行时间为3ms):
struct ListNode* reverseList(struct ListNode *head)
{
struct ListNode *second;
struct ListNode *third;
while (head == NULL) //!< 解引用前要判定是否为空
{
printf("The List is NULL!");
return head;
}
second = head->next;
head->next = NULL;
while (second != NULL) //!< 循环,每次向后挪一个
{
third = second->next;
second->next = head;
head = second;
second = third;
}
return head;
}
本文深入探讨了LeetCode上的经典问题——链表反转算法,包括问题阐述、代码实现以及效率分析。通过实例代码展示了如何将单向链表中的元素进行反置操作,提供了一种高效解决此类问题的方法。
130

被折叠的 条评论
为什么被折叠?



