剑指offer之反转链表
反转链表
https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking
题目
输入一个链表,反转链表后,输出新链表的表头。
思路
没有有递归也没有用迭代,显示将每个结点存储在vector数组里,然后反向构建链表,输出头节点。
代码
/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } };*/ class Solution { public: ListNode* ReverseList(ListNode* pHead) { if (!pHead) { return nullptr; } vector<ListNode *> list; ListNode* pLinked=pHead; while (pLinked->next != NULL) { list.push_back(pLinked); pLinked = pLinked->next; } list.push_back(pLinked); pLinked = list[list.size()-1]; pHead = pLinked; for (int i = list.size()-2; i >= 0; i--) { pLinked->next = list[i]; pLinked = pLinked->next; } pLinked->next = NULL; return pHead; } };