翻转链表

    xiaoxiao2021-03-25  106

    问题描述:

    翻转一个链表

    样例:

    给出一个链表1->2->3->null,这个翻转后的链表为3->2->1->null

    思路:

           新建链表,进行赋值交换,注意temp暂存。

    代码:

    /**  * Definition of ListNode  *   * class ListNode {  * public:  *     int val;  *     ListNode *next;  *   *     ListNode(int val) {  *         this->val = val;  *         this->next = NULL;  *     }  * }  */ class Solution { public:     /**      * @param head: The first node of linked list.      * @return: The new head of reversed linked list.      */     ListNode *reverse(ListNode *head) {          ListNode *dummy= NULL;         while(head!=NULL) {             ListNode *temp=head->next;             head->next=dummy;             dummy=head;             head=temp;         }         return dummy;         // write your code here     } };

    个人感悟:

      while里的语句注意先后顺序,不可颠倒。

    转载请注明原文地址: https://ju.6miu.com/read-24366.html

    最新回复(0)