双向链表之插入

// Double Linked List
typedef struct Node{
	int value;
	Node *next;
	Node *prev;
}Node;

Node *doubleLink_Insert(Node *pHead, int value)
{
	// New
	Node *newNode = (Node *)malloc(sizeof(Node));
	newNode->value = value;
	newNode->next = NULL;
	newNode->prev = NULL;

    // Head is null
	if (pHead == NULL)
	{
		pHead = newNode;
		return pHead;
	}

	// Insert front
	if (pHead->value >= value)
	{
		newNode->next = pHead;
		pHead->prev = newNode;
		pHead = newNode;
		return pHead;
	}
	Node *temp = pHead;
	// 方法一 与方法二效果相同,但这里只会在temp后面进行插入
	while(temp->next != NULL && temp->next->value < value)
	{
		temp = temp->next;
	}

	if (temp->next == NULL)
	{
		temp->next = newNode;
		newNode->prev = temp;
	}
	else
	{
		newNode->next = temp->next;
		newNode->prev = temp;
		temp->next->prev = newNode;
		temp = newNode;
	}
    return pHead;
#ifdef TEST // 方法二 while (temp != NULL) { if (temp->value <= value) { if(temp->next != NULL) temp = temp->next; else { //Insert back 在temp的后面插入 temp->next = newNode; newNode->prev = temp; return pHead; } } else { // insert front 在temp之前插入 newNode->next = temp; newNode->prev = temp->prev; temp->prev->next = newNode; temp->prev = newNode; return pHead; } } #endif } int main() { int data[MAX_SIZE] = {5, 4, 3, 2, 1};//{0, 0, 1, 4, 5, 5, 7, 8, 10, 9}; char sizeofT[] = "a"; examSinfor(sizeofT); int length = 0; Node *pHead = NULL; for (int i = 0; i < 15; ++i) { pHead = doubleLink_Insert(pHead, i); } for (int j = 0; j < 15; ++j) { pHead = doubleLink_Insert(pHead, j); } //pHead = doubleLink_Insert(pHead, 2); Node *temp = pHead; while (temp) { cout << temp->value << " "; temp = temp->next; } return 0; }

  

posted @ 2012-09-20 20:28  小兵传奇  阅读(275)  评论(0编辑  收藏  举报