当前位置:网站首页>Reverse linked list

Reverse linked list

2022-06-12 05:29:00 cbdgz

Punch in one question every day

2020.12.20
Enter a linked list , After reversing the list , Output the header of the new linked list .

Their thinking :

In fact, it is a stack like method , Press each point of the original list into the new list like a stack ( For the convenience of understanding, I said the new linked list , But it doesn't actually create a new linked list ).

/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } };*/
class Solution {
    
public:
    ListNode* ReverseList(ListNode* pHead) {
    
        ListNode *ansLink=NULL;
        ListNode *cur=pHead;
        ListNode *nex=NULL;
        while(NULL!=cur)
        {
    
           nex=cur->next;
           cur->next=ansLink;
           ansLink=cur;
           cur=nex;
        }
        return ansLink;

    }
};
原网站

版权声明
本文为[cbdgz]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203010616200714.html