反转链表的相关内容之前就有所了解了。大概就是先搞一个空的结点,然后让所有的指向都调转方向。
看一下题:
Q:反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
先写了一个简单,容易想到的,就是把每个结点的next改成前面的结点。可以参考下面这篇文章。
链表逆序
/**
* 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) {
ListNode *current = head;
ListNode *tmp, *output = NULL;
while (current)
{
tmp = current->next;
current->next = output;
output = current;
current = tmp;
}
return output;
}
};
然后发现运行时间还挺长的。
在评论里发现一个不错的答案,速度很快,
/**
* 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) {
ListNode *last=NULL,*next=head;
while(next)
{
next = head->next;
head->next = last;
last = head;
head = next?next:head;
}
return head;
}
};
仔细看了一下,发现思路其实差不多,时间上的差异,可能是因为第一个我要返回的是新建的output,而第二个是直接在原来的基础上改的。