【C语言】反转链表

【C语言】反转链表,第1张

目录
  • 迭代法
  • 递归法

迭代法
// *
//  * struct ListNode {
//  *	int val;
//  *	struct ListNode *next;
//  * };
//  *


/**
 * 
 * @param pHead ListNode类 
 * @return ListNode类
 */
struct ListNode* ReverseList(struct ListNode* pHead ) {
    //empty or only one node
    if(pHead == NULL || pHead->next == NULL)
        return pHead;
    
    struct ListNode* node_before = NULL;
    struct ListNode* node = pHead; 
    struct ListNode* node_after = pHead->next; 
    
    while(1){
        node->next = node_before;
        if(node_after == NULL)
            break;
        //平移指针
        node_before = node;
        node = node_after;
        node_after = node_after->next;
    }
    pHead = node;
    return pHead;
}
递归法
// *
//  * struct ListNode {
//  *	int val;
//  *	struct ListNode *next;
//  * };
//  *



/**
 * 
 * @param pHead ListNode类 
 * @return ListNode类
 */
struct ListNode* ReverseList(struct ListNode* pHead ) {
    if(pHead == NULL || pHead->next == NULL)
        return pHead;
    
    struct ListNode* newHead = ReverseList(pHead->next);
    
    pHead->next->next =pHead;
    pHead->next = NULL;
    
    return newHead;
}

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/867282.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-12
下一篇2022-05-12

发表评论

登录后才能评论

评论列表(0条)

    保存