Reverse a singly linked list.

分析

一开始写的时候总感觉没抓到要点,然后想起上数据结构课的教材上有这道题,翻开书一看完就回忆起来了,感觉解法挺巧妙的,不比讨论区的答案差。

这道题是放在链栈后面的,用的也是链栈的思想:

依次将原来栈中的元素出栈,并插入到初值为空的另一个链栈中,这样,当原栈为空时,另一个栈就是原来栈中元素的逆序。

代码如下:

/**
 * 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) {
       ListNode* p = NULL;  //empty "stack"
       ListNode* u; 
       ListNode* l = head;      //point to original list
       while(l){    //if not NULL
           u = l;   //u points to l
           l = l -> next;   //l points to next
           u -> next = p;   //push the node into "stack" p
           p = u;   //modify the top pointer
       }
       head = p;    //no effect to answer,but it's a good habbit
       return p;    
    }
};

相关文章:

  • 2021-06-07
  • 2021-09-14
  • 2022-12-23
  • 2020-02-14
  • 2019-09-17
  • 2021-08-20
  • 2021-10-14
  • 2021-10-13
猜你喜欢
  • 2021-10-20
  • 2021-09-14
  • 2021-07-26
  • 2021-08-02
  • 2021-06-09
  • 2021-05-27
  • 2021-05-28
相关资源
相似解决方案