剑指offer-反转链表

问题

题目:[剑指offer-反转链表]

思路

两种办法,头插法或者就地置逆。

代码

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};*/
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        if(!pHead)
            return NULL;
        ListNode* pre = NULL; // 一定要初始化为空
        while(pHead){
            ListNode* pNext = pHead->next;
            pHead->next = pre;

            pre = pHead;
            pHead = pNext;
        }

        ListNode* head = pre;
        while( head ){ std::cout << head->val; head=head->next; }
        return pre;
     }
};

你可能感兴趣的:(LeetCode刷题,剑指offer)