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;
}