剑指Offer-16-翻转链表

来源:互联网 发布:java log4j level 编辑:程序博客网 时间:2024/05/19 16:48

题目:
定义一个函数,输入一个链表的头结点,翻转该链表并输出翻转后的链表。
思路:
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;}
0 0
原创粉丝点击