双向链表的插入算法

来源:互联网 发布:c语言能做界面吗 编辑:程序博客网 时间:2024/05/22 19:10

该实现方法为《C与指针》上的方法!自己为了学习按照该书中给出的思路重新实现并测试了一下!以供以后学习之用!

算法要求:

实现一个双向链表,将给定值插入到链表中,并且保证链表中没有相同的值。

如果要插入的值已经在链表中,直接返回(0)。

如果没有内存可以分配,直接返回(-1);

如果成功插入,直接返回(1);

 

#include <iostream>
using namespace std;

typedef struct Node{
 struct Node* fwdP;
 struct Node* bwdP;
 int value;
}NODE_ST;

NODE_ST rootNode={0,0,0};


int InsertNodeToTwoWayLinkedList(NODE_ST* rootnodeP,int val)
{
 NODE_ST* thisNodeP = rootnodeP;
 NODE_ST* nextNodeP = NULL;
 NODE_ST* newNodeP = NULL;

 /*检测链表中是否已经有该值存在,如果有直接返回零*/
 while((nextNodeP=thisNodeP->fwdP)!= NULL)
 {
  if(nextNodeP->value == val)
   return 0;
  if(nextNodeP->value > val)
   break;

  thisNodeP = nextNodeP;

 }

 newNodeP = new NODE_ST;
 if(NULL == newNodeP)
  return -1;
    newNodeP->value = val;

 
 if( NULL != nextNodeP) //(1)插在链表的非尾部
 {
  if( rootnodeP != thisNodeP) //(1.1)插在链表非头部.
  {
   thisNodeP->fwdP = newNodeP;
   newNodeP->fwdP = nextNodeP;
   nextNodeP->bwdP = newNodeP;
   newNodeP->bwdP = thisNodeP;
  }else{                                   // (1.2)插在链表头部
   thisNodeP->fwdP = newNodeP;
   newNodeP->fwdP = nextNodeP;
   nextNodeP->bwdP = newNodeP;
   newNodeP->bwdP = NULL;
  }
 }else{                           //(2)插在链表尾部

  if(rootnodeP != thisNodeP) //(2.1)非空链表并且插在链尾
  {
   thisNodeP->fwdP = newNodeP;
   rootnodeP->bwdP = newNodeP;
   newNodeP->fwdP = NULL;
   newNodeP->bwdP = thisNodeP;

  }else{                                //(2.2)这种情况为空链表(空链表并且插在链头)
   thisNodeP->fwdP = newNodeP;
   thisNodeP->bwdP = newNodeP;
   newNodeP->fwdP = NULL;
   newNodeP->bwdP = NULL;

  }

 }
 return 1;


}
int _tmain(int argc, _TCHAR* argv[])
{
 InsertNodeToTwoWayLinkedList(&rootNode,4);
 InsertNodeToTwoWayLinkedList(&rootNode,2);
 InsertNodeToTwoWayLinkedList(&rootNode,1);
 InsertNodeToTwoWayLinkedList(&rootNode,7);
 InsertNodeToTwoWayLinkedList(&rootNode,5);
 InsertNodeToTwoWayLinkedList(&rootNode,7);

 NODE_ST* currentNodeP = &rootNode;
 //正向测试链表
 for(;currentNodeP->fwdP!= NULL; currentNodeP= currentNodeP->fwdP)
 cout<< currentNodeP->fwdP->value << endl;

 //反向测试链表
 currentNodeP = &rootNode;
 for(;currentNodeP->bwdP!= NULL; currentNodeP= currentNodeP->bwdP)
  cout<< currentNodeP->bwdP->value << endl;

 return 0;
}

点评:

与单向链表不同,这里使用的是一个根节点,而不是根指针!根节点中的fwdP字段指向链表的首节点,根节点的bwdP字段指向链表的尾节点。

0 0
原创粉丝点击