雙向鏈表元素的插入

來源:互聯網
上載者:User

 struct Node<br />{<br /> int Data;<br /> struct Node* prior;<br /> struct Node* next;<br />};</p><p>/**<br />* @brief 該函數實現了在帶頭結點雙鏈表中第i個結點之前插入元素<br />* @param[in] head 待插入結點鏈表<br />* @param[in] i 待插入結點位置<br />* @param[in] e 待插入結點值</p><p>* @author wlq_729@163.com<br />* http://blog.csdn.net/rabbit729<br />* @version 1.0<br />* @date 2009-03-09<br />*/<br />int InsertDoubleList(Node* head, const int i, const int e)<br />{<br /> assert(head);<br /> if (head->next == NULL)<br /> {<br /> return -1;<br /> }</p><p> // 尋找待插入結點位置<br /> int j = 0;<br /> Node* p = head;<br /> while ((p->next != NULL) && (j < i))<br /> {<br /> p = p->next;<br /> j++;<br /> }</p><p> // 插入結點<br /> Node* q = new Node;<br /> assert(q);<br /> q->Data = e;<br /> q->prior = p->prior;<br /> p->prior->next = q;<br /> q->next = p;<br /> p->prior = q;<br /> return 0;<br />}</p><p>/**<br />* @brief 該函數實現了在帶頭結點雙鏈表中與給定值相等的第一個結點前插入結點<br />* @param[in] head 待插入結點鏈表<br />* @param[in] e 待插入結點的位置<br />* @param[in] data 待插入結點值</p><p>* @author wlq_729@163.com<br />* http://blog.csdn.net/rabbit729<br />* @version 1.0<br />* @date 2009-03-09<br />*/<br />int InsertDoubleList1(Node* head, const int e, const int data)<br />{<br /> assert(head);<br /> if (head->next == NULL)<br /> {<br /> return -1;<br /> }</p><p> // 尋找待插入結點位置<br /> Node* p = head->next;<br /> while ((p != NULL) && (p->Data != e))<br /> {<br /> p = p->next;<br /> }</p><p> // 插入結點<br /> if((p != NULL) && (p->Data == e) )<br /> {<br /> Node* q = new Node;<br /> assert(q);<br /> q->Data = e;<br /> q->prior = p->prior;<br /> p->prior->next = q;<br /> q->next = p;<br /> p->prior = q;<br /> return 0;<br /> }<br /> else<br /> {<br /> cout<<"Could not find data!"<<endl;<br /> return -1;<br /> }<br />}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.