单链表反转

typedef struct ListNode
{
    int data;
    ListNode *pNext;

    ListNode(int data)
    {
        this->data = data;
        pNext = NULL;
    }
} *PListNode;

PListNode reverseList(PListNode head)
{
    if (head == NULL || head->pNext == NULL) {
        return head;
    }

    PListNode curNode = head;
    PListNode nextNode = head->pNext;
        //注意这里一定要写成nextNode != NULL,而不要写成curNode->pNext!= NULL,
    while (nextNode != NULL)
    {
        PListNode pTemp = nextNode->pNext;
        nextNode->pNext = curNode;
        curNode = nextNode;
        nextNode = pTemp;
    }
    head->pNext = NULL;  //翻转完成后将原来的第一个节点的pNext指针赋值为NULL,会死循环的
    return curNode; 
}

void printList(PListNode head)
{
    PListNode node = head;
    while (node != NULL)
    {
        cout << node->data << " ";
        node = node->pNext;
    }
    cout << endl;
}

void main() {
    int arr[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    PListNode head = new ListNode(0);
    PListNode next = head;
    for (int i = 1; i < 10; i++)
    {
        PListNode node = new ListNode(i);
        next->pNext = node;
        next = node;
    }

    cout << "链表反转前" << endl;
    printList(head);

    head = reverseList(head);

    cout << "链表反转后" << endl;
    printList(head);

    getchar();
}

你可能感兴趣的:(单链表反转)