给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
迭代法
/*** 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(head==nullptr || head->next==nullptr) return head;// //ListNode* newhead = reverseList(head->next);//head->next->next = head;//head->next = nullptr;ListNode* pre = nullptr; // 前一个节点ListNode* cur = head; // 当前指针节点while(cur){ListNode* tmp = cur->next; // 保存当前节点的下一个结点cur->next = pre;pre = cur; // 前指针后移cur=tmp; // 返回当前结点的下一个结点}return pre;}
};