reverse linked list

Input a linked list, after reversing the linked list, output the header of the new linked list.

The recursive method is actually very clever. It uses recursion to go to the end of the linked list, and then updates the next value of each node to realize the inversion of the linked list. The value of newhead has not changed, it is the last node of the linked list, so after reversing, we can get the head of the new linked list.
Pay attention to thinking about common caveats about linked list problems:

1. If the input head node is NULL, or the entire linked list has only one node

2. Consideration of chain breakage

//第一种方法是:非递归方法
/*
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* pNode=pHead;//当前指针
        ListNode* pReverseHead=NULL;//新链表的头指针
        ListNode* pPrev=NULL;//当前指针的前一个结点
         
        while(pNode!=NULL){
    
    //当前结点不为空时才执行
            ListNode* pNext=pNode->next;//链断开之前一定要保存断开位置后边的结点
             
            if(pNext==NULL)//当pNext为空时,说明当前结点为尾节点
                pReverseHead=pNode;
  
            pNode->next=pPrev;//指针反转
            pPrev=pNode;
            pNode=pNext;
        }
        return pReverseHead;
    }
}
 
//第二种方法是:递归方法 /*
struct ListNode {
    
    
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    
    
    }
};*/
class Solution {
    
    
public:
    ListNode* ReverseList(ListNode* pHead) {
    
    
        //如果链表为空或者链表中只有一个元素
        if(pHead==NULL||pHead->next==NULL) return pHead;
         
        //先反转后面的链表,走到链表的末端结点
        ListNode* pReverseNode=ReverseList(pHead->next);
         
        //再将当前节点设置为后面节点的后续节点
        pHead->next->next=pHead;
        pHead->next=NULL;
         
        return pReverseNode;
         
    }
};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325678963&siteId=291194637