一.题目解析算法解析:结合画图和头插代码就很好理解了二.代码编写:/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* reverseList(ListNode* head) { if(headnullptr||head-nextnullptr)return head; ListNode*newheadnew ListNode(0); ListNode*curhead; while(cur!nullptr) { ListNode*nextcur-next;//注意顺序和位置 cur-nextnewhead-next; newhead-nextcur; curnext; } curnewhead-next; delete newhead; return cur; } };
优选算法_翻转链表_头插法_C++
一.题目解析算法解析:结合画图和头插代码就很好理解了二.代码编写:/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* reverseList(ListNode* head) { if(headnullptr||head-nextnullptr)return head; ListNode*newheadnew ListNode(0); ListNode*curhead; while(cur!nullptr) { ListNode*nextcur-next;//注意顺序和位置 cur-nextnewhead-next; newhead-nextcur; curnext; } curnewhead-next; delete newhead; return cur; } };