Linked List Exercise [2]

The study arrangement is based on "Code Caprice"~

 

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) 
    {
        ListNode*pre=NULL;//定义一个空指针
        ListNode*cur=head;//定义一个指向头的指针
        ListNode*temp;//用来保存原来的cur的下一个结点
        while(cur)
        {
            temp=cur->next;//保存cur的下一个结点
            cur->next=pre;将现在的cur下一个结点指向pre
            pre=cur;//随后pre指向cur
            cur=temp;//cur指向原来的下一个结点
        }
        return pre;


    }
};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324120926&siteId=291194637