zoukankan      html  css  js  c++  java
  • 双向链表之插入

    // 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; }

      

  • 相关阅读:
    C. Tanya and Toys_模拟
    B. Qualifying Contest_排序
    A. Round House_数学问题
    广搜,深搜,单源最短路径,POJ(1130),ZOJ(1085)
    广搜,智能拼图(ZOJ1079)
    类似LIS+贪心(ZOJ1025)
    字符串处理(POJ1782)
    打表格,字符串处理,POJ(2136)
    二进制字符串匹配
    括号匹配问题
  • 原文地址:https://www.cnblogs.com/dawnWind/p/2695886.html
Copyright © 2011-2022 走看看