面试题26 复杂链表的复制

struct ListNode{

	int val;

	ListNode *next;

	ListNode *sibling;

	ListNode(int a):val(a),next(NULL),sibling(NULL){}

};



void CloneNode(ListNode * head)

{

	ListNode *pNode = head;

	while(pNode != NULL){

		LiseNode *p = new ListNode(pNode->val);

		p->next = pNode->next;

		pNode->next = p;

		pNode = p->next;

	}

}

void CloneRelation(ListNode * head)

{

	if(head == NULL) return;

	ListNode *pNode, *cNode;

	pNode = head;

	while(pNode != NULL){

		cNode = pNode->next;

		if(pNode->next != NULL)

			cNode->sibling = pNode->sibling->next;

        pNode = cNode->next;

	}

}



ListNode * Reconection(ListNode * head){



	ListNode *chead, *cNode, *pNode,*p;

	if(head == NULL) return;

	chead = head->next;

	p = chead->next;

	pNode = head;

	cNode = chead;

	while(p != NULL){

		pNode->next = p;

		cNode->next = p->next;

		pNode = pNode->next;

		cNode = cNode->next;

		p = cNode->next;

	}

	pNode->next = NULL;

	cNode->next = NULL;

	

	return chead;

}



ListNode * Copy(ListNode * head){

		

	if(head== NULL) return head;

	CloneNode(head);

	CloneRelation(head);

	return reConnection(head);

}

  

你可能感兴趣的:(面试题)