単一チェーンテーブルの作成、割り当てC++の例
1393 ワード
#include
using namespace std;
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
ListNode* CloneList(ListNode* pHead){
ListNode* pNode = pHead;
ListNode* pCloneHead, *pCloneNode;
if (pNode) {
pCloneNode = new ListNode(pNode->val);
pCloneNode->next = NULL;
pHead = pCloneNode;
pNode = pNode->next;
}
while (pNode) {
ListNode* pTemp = new ListNode(pNode->val);
pCloneNode->next = pTemp;
pCloneNode = pTemp;
pCloneNode->next = NULL;
pNode = pNode->next;
}
return pCloneHead;
}
void printList(ListNode* pHead){
ListNode* pTraverse = pHead;
if (!pTraverse) {
return;
}
while (pTraverse) {
cout<< pTraverse->val << " ";
pTraverse = pTraverse->next;
}
cout<< endl;
}
ListNode* CreatList(){
ListNode* pNode = new ListNode(0);
pNode->next = NULL;
ListNode* pHead = pNode;
for (int i = 1; i < 5; i++) {
ListNode* pTemp = new ListNode(i);
pNode->next = pTemp;
pNode = pTemp;
}
return pHead;
}
int main(){
ListNode* p = CreatList();
printList(p);
ListNode* pClone = CloneList(p);
printList(pClone);
}