标签:c++ 复杂链表的复制
de关于复杂链表:
向复杂链表的复制。一个链表的每个节点,有一个指向next指针指向下一个节点,还有一个bext2指针指向这个链表中的一个随机节点或者NULL
实现代码如下:
#pragma once #include<stdio.h> #include<malloc.h> typedef int DataType; typedef struct HardList { DataType Data; struct HardList *next; struct HardList *next2; }HardList; HardList* _BuyNode(DataType x)//初始化 { HardList *tmp = (HardList*)malloc(sizeof(HardList)); tmp->Data = x; tmp->next = NULL; tmp->next2 = NULL; return tmp; } void PushBack(HardList* &pHead, DataType x) { if (pHead == NULL) pHead = _BuyNode(x); else { HardList *tial = pHead; while (tial->next != NULL) { tial = tial->next; } tial->next = _BuyNode(x); } } HardList* Find(HardList*& pHead, DataType x) { HardList* cur = pHead; while (cur) { if (cur->Data == x) { return cur; } cur = cur->next; } return NULL; } void PrintSlist(HardList* &pHead) { if (pHead == NULL) { printf("空链表\n"); return; } HardList *cur = pHead; while (cur) { printf("%d->", cur->Data); cur = cur->next; } printf("NULL\n"); } HardList* CopyList(HardList* &pHead) { if (pHead == NULL) return NULL; HardList *cur = pHead; while (cur) { HardList *tmp = _BuyNode(cur->Data); //tmp->next2= tmp->next = cur->next; cur->next = tmp; cur = cur->next->next;//cur=null } //HardList *tmp = _BuyNode(cur->Data); //tmp->next = cur->next; //cur->next = tmp;//完成复制 //下一步完成next2的复制 cur = pHead; while (cur) { HardList *p = cur->next; if (cur->next2&&p) { p->next2 = cur->next2->next; } cur = cur->next->next; }//完成next2的复制 //拆分 HardList *p = pHead; HardList *q = p->next; HardList *ret = pHead->next; while (p->next->next) { //if (p->next) q = p->next; p->next = q->next; p = p->next; q->next = p->next; //p = p->next; } p->next = NULL; PrintSlist(ret); return ret; }
每个节点的结构为:
typedef struct HardList
{
DataType Data;
struct HardList *next;
struct HardList *next2;
}HardList;
先创建好单链表,考虑next2这个分量,则需要O(n^2)的时间复杂度
通过对每一个节点进行复制并插入到原节点的后方,则复制的节点的next2 指针指向的节点则在原节点next2指针的的下一个位置,这样就能够找到复制的节点的next2 指针,然后将奇数位置与偶数位置的节点进行拆分,这样完成了复杂链表的复制
题的思路在于 如何找到节点的next2指针,我们将每一个指针的拷贝插入到原节点之后,这样既完成了每一个节点的复制,又能方便找到复制的链表的next2指针指向的位置:
本文出自 “10945910” 博客,请务必保留此出处http://10955910.blog.51cto.com/10945910/1749927
标签:c++ 复杂链表的复制
原文地址:http://10955910.blog.51cto.com/10945910/1749927