题目
题解
- 链表:头插法
代码
/**
* 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) {}
* };
*/
/**
* 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) {
ListNode* tail=new ListNode(-1);
ListNode* hhead=new ListNode(0,tail);
while(head!=nullptr){
tail->val=head->val;
hhead->next=tail;
tail=hhead;
ListNode* node=new ListNode(0,hhead);
hhead=node;
head=head->next;
}
return tail->next;
}
};