题目描述:
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL
思路:利用栈的先进后出的性质将链表反转,先将链表从头到尾压入栈中,然后再将栈中数据出栈,保存到新链表中
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* reverseList(ListNode* head) { if(head==nullptr) return nullptr; if(head->next == nullptr) return head; stack<int> elem; ListNode* curr = head; while(curr != NULL){ elem.push(curr->val); curr = curr->next; } curr = head; while(curr!=NULL){ curr->val = elem.top(); curr = curr->next; elem.pop(); } return head; } };