insert code for ordered double-loop list (C)
This address: Http://blog.csdn.net/caroline_wendy
Sequential double-loop list insertion, need to find the insertion position, can be used, two pointers , one in front, one in the rear.
Ensure that the previous less than equals insert value, followed by greater than or equal to the insertion value.
In special cases , insert (greater than or less than the entire list) or single node, the inferred condition is that the pointer points to the first node. You need to insert it directly.
To insert a linked list header, you need to adjust the link header node .
Code 22 lines.
Code:
/* * main.cpp * * Created on:2014.9.18 * author:spike *//*eclipse CDT, gcc 4.8.1*/#include <stdio.h> #include <stdlib.h>using namespace Std;struct listnode {listnode (int v) {value = V;prev = Null;next = NULL;} int value; listnode* prev; Listnode* next;}; listnode* createlists () {listnode* head = new ListNode (0); listnode* Node1 = new ListNode (1); listnode* Node2 = new ListNode (2); listnode* node4 = new ListNode (4); listnode* node5 = new ListNode (5); Head->prev = Node5;head->next = Node1;node1->prev = Head;node1->next = Node2 ; Node2->prev = Node1;node2->next = Node4;node4->prev = Node2;node4->next = Node5;node5->prev = Node4; Node5->next = Head;return Head;} listnode* CreateLists2 () {listnode* head = new ListNode (0); Head->prev = Head;head->next = Head;return head;} void Print (listnode* head) {listnode* node = head;printf ("%d", node->value); node = node->next;while (node! = head) {printf ("%d", node->value); node = Node->next;} printf"\ n");} listnode* Insertnode (listnode* Head, listnode* node) {if (head = = NULL | | node = = NULL) return head; listnode* PrevNode = head; listnode* NextNode = head->next;while (1) {if (Prevnode->value < Node->value &&nextnode->value & gt;= Node->value) | | (NextNode = = head)) {Prevnode->next = Node;node->prev = Prevnode;nextnode->prev = Node;node->next = NextNode;if (node->value < Head->value) {head = node;} break;} PrevNode = Prevnode->next;nextnode = Prevnode->next;} return head;} int main (void) {listnode* head = createlists (); Print (head); listnode* node = new ListNode (3); listnode* NewList = Insertnode (head, node); Print (newlist); return 0;}
Output:
Programming algorithms-Insertion code for ordered double-loop lists (C)