剑指Offer-16-翻转链表

题目:
定义一个函数,输入一个链表的头结点,翻转该链表并输出翻转后的链表。
思路:
1.使用两个指针a,b分别指向待翻转的两个结点,同时为了防止断链,使用一个指针c保存b->next指针,c=b->next。
2.a,b两个结点翻转后,令a=b,b=c。
3.循环1,2直至b为NULL。
注意:
1.头结点的next指针赋NULL
2.链表为空的情况
3.链表只有一个结点的情况


#include <iostream>
using namespace std;

struct ListNode {
    int value;
    ListNode *pNext;
};

ListNode* reverseList(ListNode *pHead) {
    //链表为空
    if(pHead == NULL) {
        return NULL;
    }
    //链表只包含一个结点
    if(pHead->pNext == NULL) {
        return pHead;
    }
    //链表包含多个结点

    //pLeft与pRight两个结点翻转
    ListNode *pLeft = pHead;
    ListNode *pRight = pHead->pNext;

    //PNode的作用为防止断链,记录pRight的next指针
    ListNode *pNode = NULL;

    //第一个结点的next指针赋NULL
    pHead->pNext = NULL;

    //翻转链表
    while(pRight) {
        pNode = pRight->pNext;
        pRight->pNext = pLeft;
        pLeft = pRight;
        pRight = pNode;
    }
    return pLeft;
}

/**
 * 向链表中插入结点
 */
void insertList(ListNode **pHead,ListNode *value) {
        ListNode *head = *pHead;
        if(head == NULL) {
            *pHead = value;
        }
        else {
            while(head->pNext != NULL) {
                head = head->pNext;
            }
            head->pNext = value;
        }
}

/**
 * 向链表中插入结点
 */
void insertList(ListNode **pHead,int value) {
    ListNode *p = new ListNode();
    p->value = value;
    p->pNext = NULL;
    insertList(pHead,p);
}

/**
 * 打印链表
 */
void print(ListNode *p) {
    while(p) {
        cout<<p->value<<" ";
        p = p->pNext;
    }
    cout<<endl;
}

int main() {
    //测试实例
    //1.普通多个结点链表翻转
    ListNode *head = NULL;
    insertList(&head,1);
    insertList(&head,2);
    insertList(&head,3);
    head = reverseList(head);
    print(head);

    //2.空链表翻转
    ListNode *head1 = NULL;
    head1 = reverseList(head1);
    print(head1);

    //3.单个结点的链表翻转
    ListNode *head2 = NULL;
    insertList(&head2,1);
    head2 = reverseList(head2);
    print(head2);

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值