反轉一個單鏈表, 示例: 輸入: 1->2->3->4->5->NULL 輸出: 5->4->3->2->1->NULL 來源:力扣(LeetCode) 鏈接:https://leetcode-cn.com/problems/reverse-linked-list 著作權歸領扣網路所有,商業轉載請聯系官方授權,非商業轉載請注明出處,
1 struct ListNode { 2 int val; 3 ListNode *next; 4 ListNode(int x) : val(x), next(NULL) {} 5 }; 6 7 class Solution { 8 public: 9 ListNode* reverseList(ListNode* head) { 10 ListNode *new_head = NULL;//指向新鏈表頭節點的指標 11 while (head) { 12 //備份 head->next,因為第二步要把head->next 指向新的頭節點,不保存就找不到了 13 ListNode *next = head->next; 14 head->next = new_head;//更新 head->next,指向新鏈表的頭節點 15 new_head = head;//移動 new_head,指向新節點 16 head = next; 17 } 18 return new_head; 19 } 20 };測驗
1 int main(int argc, const char * argv[]) { 2 ListNode a(1); 3 ListNode b(2); 4 ListNode c(3); 5 ListNode d(4); 6 ListNode e(5); 7 a.next = &b; 8 b.next = &c; 9 c.next = &d; 10 d.next = &e; 11 Solution solve; 12 ListNode *head = &a; 13 cout << "Before\n"; 14 while (head) { 15 cout <<head->val<<endl; 16 head = head->next; 17 } 18 head = solve.reverseList(&a); 19 cout << "After\n"; 20 while (head) { 21 cout <<head->val<<endl; 22 head = head->next; 23 } 24 25 return 0; 26 }View Code
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/137708.html
標籤:其他
上一篇:螞蟻Java三面:二叉樹+HTTPS加密+自旋鎖+快取穿透(送答案)
下一篇:用js刷劍指offer(丑數)
