题解 | #反转链表#C++
反转链表
http://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
第一种方法:反向赋值
定义两个节点指针pre为反转之后链表的头,tmp用来保存当前节点的下一节点,先将pre初始化为空,这样循环将phead当前节点指向pre,再将当前节点保存为pre,不断的反向赋值。
第二种方法:利用stl容器和算法,将节点全部放入vector中保存,然后反转,最后在把vector中的元素取出。
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead)
{
/*
ListNode* pre = NULL,*tmp;
while(pHead)
{
tmp = pHead->next;
pHead->next = pre;
pre = pHead;
pHead = tmp;
}
return pre;*/
if (!pHead)
return pHead;
vector<ListNode*> iv;
while (pHead)
{
iv.push_back(pHead);
pHead = pHead->next;
}
reverse(iv.begin(), iv.end());
ListNode* head = iv[0];
ListNode* cur = head;
for (int i = 1; i < iv.size(); i++)
{
cur->next = iv[i];
cur = cur->next;
}
cur->next = nullptr;
return head;
}
}; 