剑指offer24.反转链表

题目描述

输入一个链表,反转链表后,输出新链表的表头。

完整代码

借助栈来实现

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        //借助栈实现链表的反转
        stack<int> num;
        ListNode* p;
        p=pHead;
        while(p){
            num.push(p->val);
            p=p->next;
        }
        p=pHead;
        while(p){
            p->val=num.top();
            num.pop();
            p=p->next;
        }
        return pHead;
    }
};

直接反转指针

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        //原来p->next,指向next,现在让其指向pre
        ListNode* p,*pre,*nextt;
        pre=NULL;
        p=pHead;
        while(p){
            nextt=p->next;
            p->next=pre;//反转指针
            pre=p;
            p=nextt;
        }
        
        return pre;
    }
};

递归翻转

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        //递归翻转
        if(pHead == NULL)
            return NULL;
        ListNode* p = pHead;
        while(p->next != NULL){
            p = p->next;
        }
        reverse(pHead, NULL);
        return p;
    }
private:
    void reverse(ListNode *p, ListNode* pre){
        if(p == NULL)
            return;
        reverse(p->next, p);
        p->next = pre;
    }
};

你可能感兴趣的:(c++,#,c++链表,剑指offer)