对于链倒排序写了三种:
1 原地反转法 https://blog.csdn.net/abk921/article/details/112056711
2 递归法 https://blog.csdn.net/abk921/article/details/112343925
3 头部插入法
这次实现的是头部插入法实现总结:
自己画的示意图如下:
代码是:
/**
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution
{
public:
ListNode *reverseList(ListNode *head)
{
ListNode tmp(0);
ListNode *cur = head, * nptr = NULL;
while (cur)
{
nptr = cur->next;
cur->next = tmp.next;
tmp.next = cur;
cur = nptr;
}
return tmp.next;
}
}