剑指offer----逆转链表

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
//递归版本
class Solution1 {
public:
    ListNode* ReverseList(ListNode* pHead) {
        if(pHead== NULL||pHead->next == NULL)
            return pHead;
        ListNode * p  = ReverseList(pHead->next);
        pHead->next->next = pHead;
        pHead->next = NULL;
        return p;//只返回最后一个节点
    }
};

//非递归版本
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        if(pHead== NULL||pHead->next == NULL)
            return pHead;
        ListNode *pre = pHead;
        ListNode * last  = NULL;
        ListNode * next  = NULL;
        while(pre != NULL)
        {
            next = pre->next;
            pre->next = last;
            last = pre;
            pre = next;
        }
        return last;
    }
};

猜你喜欢

转载自blog.csdn.net/run32875094/article/details/80201115