剑指offer面试题24--反转链表

1.基本思想:

设指针pNode,指当前节点CurrentNode,既然要反转就让CurrentNode的next指针指CurrentNode的前驱节点设为preNode,还要循环处理pNode在原链表的next节点,所以反转前事先保留pNode->next以便循环。也就是程序开始前需要定义三个指针pNode,preNode,nextNode

2.写代码中考虑几种情况

  (1)输入的链表为空   (2)原链表只有一个节点   (3)原链表有多个节点

这几种情况在写完代码后要自己心里验证下

3.代码:

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        
        if(pHead==nullptr)
            return nullptr;
        
        ListNode* preNode=nullptr;
        ListNode* ResultReverseNode=pHead;
        ListNode* Node=pHead;
        ListNode* nextNode=nullptr;
        
        while(Node!=nullptr)
        {
            ResultReverseNode=Node;
            nextNode=Node->next;
           // nextNode->next=Node;
            Node->next=preNode;
            
            if(nextNode==nullptr)
                return ResultReverseNode;
            
            preNode=Node;
            Node=nextNode;
            
        }
        
        return ResultReverseNode;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_34793133/article/details/81010536
今日推荐