1 题目描述
输入一个链表,反转链表后,输出新链表的表头。
2 思路和方法
(1)利用栈作为中间存储,进行链表的反转,将压入的数据按先进后出的顺序弹出依次赋给链表再输出表头pHead。
(2)将当前节点数对应的下一个节点数保存tmp=pHead.next,将上个节点数last赋值给pHead.next(初始last为None)。当前节点pHead赋值给last(成为上一个节点),最后将下一个节点tmp赋值给pHead(成为当前结点)。
3 C++核心代码
3.1 入栈出栈
1 struct ListNode { 2 int val; 3 struct ListNode *next; 4 ListNode(int x) : 5 val(x), next(NULL) { 6 } 7 };*/ 8 class Solution { 9 public: 10 ListNode* ReverseList(ListNode* pHead) { 11 ListNode* p=pHead; 12 ListNode* q=pHead; 13 stack<int> s1; 14 while(p!=NULL) //先遍历链表压入栈中 15 { 16 s1.push(p->val); 17 p=p->next; 18 } 19 while(q!=NULL) //再遍历链表,将栈中数据弹出依次赋给链表 20 { 21 q->val=s1.top(); 22 s1.pop(); 23 q=q->next; 24 } 25 return pHead; //链表被更新,pHead依然指向表头 26 } 27 };
3.2 链表法
1 /* 2 struct ListNode { 3 int val; 4 struct ListNode *next; 5 ListNode(int x) : 6 val(x), next(NULL) { 7 } 8 };*/ 9 class Solution { 10 public: 11 ListNode* ReverseList(ListNode* pHead) { 12 ListNode* last; 13 ListNode* temp; 14 last = NULL; 15 while(pHead!=NULL){ 16 temp = pHead->next; 17 pHead->next = last; 18 last = pHead; 19 pHead = temp; 20 } 21 return last; 22 } 23 };
4 完整代码
1 #include <iostream> 2 3 using namespace std; 4 5 struct ListNode { 6 int val; 7 struct ListNode *next; 8 ListNode(int x) : 9 val(x), next(NULL) { 10 } 11 }; 12 13 class Solution { 14 public: 15 ListNode* ReverseList(ListNode* pHead) { 16 if (pHead == NULL) 17 { 18 return NULL; 19 } 20 21 ListNode* p_head = pHead; 22 23 ListNode* p_fast = p_head->next; 24 pHead->next = NULL; //指向null,细节 25 while (p_fast != NULL) 26 { 27 ListNode* temp = p_fast->next; 28 p_fast->next = p_head; 29 p_head = p_fast; 30 p_fast = temp; 31 } 32 return p_head; 33 } 34 }; 35 36 int main() 37 { 38 Solution *s = new Solution(); 39 //vector<int> v = { 2,4,6,1,3,5,7 }; 40 ListNode *l1 = new ListNode(1); 41 ListNode *l2 = new ListNode(2); 42 ListNode *l3 = new ListNode(3); 43 ListNode *l4 = new ListNode(4); 44 ListNode *l5 = new ListNode(5); 45 ListNode *l6 = new ListNode(6); 46 ListNode *l7 = new ListNode(7); 47 l1->next = l2; 48 l2->next = l3; 49 l3->next = l4; 50 l4->next = l5; 51 l5->next = l6; 52 l6->next = l7; 53 54 ListNode* out_list = s->ReverseList(l1); 55 56 cout << int(out_list->val) << endl; 57 58 system("pause"); 59 return 0; 60 }
参考资料
https://blog.csdn.net/aaa958099161/article/details/90049908
https://blog.csdn.net/zlb666/article/details/87641684