面试题03:反转链表

题目:输入一个链表的头结点,反转该链表,并返回反转后链表的头结点。链表结点定义如下:

struct List
{
      int       value;
      ListNode* next;
};

1、循环方法

//反转链表
List* ReverseList(List* pHead){
    List* pNode = pHead;
    List* pPre = NULL;
    List* pReverseHead = pNode;

    while (pNode != NULL){
        if (pNode->next == NULL){
            pReverseHead = pNode;
        }
        List* pNext = pNode->next;
        pNode->next = pPre;
        pPre = pNode;
        pNode = pNext;
    }
    return pReverseHead;
}

2、递归方法

void reverse(List*& p) {
    if (!p) return;
    List* rest = p->next;
    if (!rest) return;
    reverse(rest);
    p->next->next = p;
    p->next = NULL;
    p = rest;
}

你可能感兴趣的:(面试题03:反转链表)