赞
踩
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct Node { int data; struct Node *pNext; struct Node *Pre; }pNode,*ListNode; //创建结点 struct Node *Create_Node(int dat) { struct Node *pHead = (struct Node *)malloc(sizeof(pHead)); //判断是否空间申请成功 if(NULL == pHead) { return NULL; //申请失败 } //先清空间 memset(pHead,'\0',sizeof(pHead)); //赋值 pHead->data = dat; pHead->pNext = NULL; pHead->Pre = NULL; //返回结点 return pHead; } //头插法添加结点 struct Node *InsertNodeByHead(ListNode pHead,ListNode New) { if(NULL == pHead || NULL == New) { return NULL; } New->pNext = pHead->pNext; if(NULL != pHead->pNext) //头结点下一个结点不是NULL { pHead->pNext->Pre = New; } New->Pre = pHead; pHead->pNext = New; return pHead; } //尾插法添加结点 struct Node *InsertNodeByTail(ListNode pHead,ListNode New) { struct Node *Temp = pHead; while(NULL != Temp->pNext) { Temp = Temp->pNext; } New->pNext = Temp->pNext; New->Pre = Temp; Temp->pNext = New; return Temp; } //根据数据查找某个结点 struct Node *FindNodeByData(ListNode pHead,int dat) { struct Node *Temp = pHead; while(NULL != Temp->pNext) { Temp = Temp->pNext; if(Temp->data == dat) { return Temp; //找到数据 } } return NULL; //循环完还没有找到 } //删除结点 int DeleteNodeByData(ListNode pHead,int dat) { struct Node *Temp = FindNodeByData(pHead,dat); if(NULL == Temp) { return 0; } //进行删除 Temp->Pre->pNext = Temp->pNext; if(NULL != Temp->pNext) //判断该结点的下一个是否为空 { Temp->pNext->Pre = Temp->Pre; } free(Temp); return 1; } void PrintNode(ListNode pHead) { struct Node *Temp = pHead; int num = 1; while(NULL != Temp->pNext) { Temp = Temp->pNext; printf("node %d:%d\n",num,Temp->data); num++; } } int main(void) { ListNode pH = NULL; pH = Create_Node(0); InsertNodeByHead(pH,Create_Node(12)); InsertNodeByHead(pH,Create_Node(3)); InsertNodeByHead(pH,Create_Node(45)); InsertNodeByTail(pH,Create_Node(23)); InsertNodeByTail(pH,Create_Node(5)); InsertNodeByTail(pH,Create_Node(67)); PrintNode(pH); printf("--------------删除结点后------------\n"); DeleteNodeByData(pH,67); PrintNode(pH); return 0; }
运行结果
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。