O(n)复杂度实现链表反转

  • 输入一个链表,反转链表后,输出新链表的表头。

  • 插头法思想:
    将头结点断开,把后面的节点依次取出,插入到头部,可实现O(n)复杂度链表反转效果。
    在这里插入图片描述

  • 演示代码

#include<iostream>
#include<stdlib.h>
using namespace std;
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};

ListNode* ReverseList(ListNode* pHead) {

    if(!pHead)
        return NULL;
    if(!pHead->next)
        return NULL;
    ListNode* first = pHead->next;
    ListNode* second = pHead->next;
    pHead->next=NULL;
    while(first)
    {
        second=second->next;
        first->next=pHead;
        pHead=first;
        first=second;
    }
    return pHead;

}

int main()
{

    ListNode* head;
    ListNode * p =(ListNode*) malloc(sizeof(ListNode));;
    head = p;
    for(int i = 0;i<5;i++)
    {
        ListNode* point =(ListNode*) malloc(sizeof(ListNode));
        point->val = i;
        point->next=NULL;
        p->next=point;
        p=point;
    }

    p=ReverseList(head);
    while(p)
    {
        cout<<p->val<<endl;
        p=p->next;
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/Leader_wang/article/details/83215858