标签:style os io 2014 for re c 代码
核心代码:
//在O(1)时间删除结点。注:必须保证pDel为链表中的结点 void DeleteNode(List *list,pNode pDel) { if(*list == NULL || pDel == NULL) { return; } //不是最后一个节点 if(pDel->next != NULL) {//复制pDel后边的结点的值,并删除pDel后边的结点 pNode pTemp = pDel->next; pDel->data = pTemp->data; pDel->next = pTemp->next; free(pTemp); pTemp = NULL; }else if(*list == pDel)//链表仅有一个结点 { free(pDel); pDel = *list = NULL; }else//是最后一个结点 { pNode pTemp = *list; while(pTemp->next != pDel) { pTemp = pTemp->next; } pTemp->next = NULL; free(pDel); pDel = NULL; } }
/* 在O(1)时间内删除单向链表结点 by Rowandjj 2014/7/25 */ #include<iostream> using namespace std; typedef struct _NODE_ { int data; struct _NODE_ *next; }Node,*pNode,*List; void AddToTail(List *list,int data) { pNode pNew = (pNode)malloc(sizeof(Node)); if(!pNew) { exit(-1); } pNew->data = data; pNew->next = NULL; if(*list == NULL) { *list = pNew; }else { pNode pTemp = *list; while(pTemp->next != NULL) { pTemp = pTemp->next; } pTemp->next = pNew; } } void Create(List *list,int n) { if(n <= 0) { return; } int data; for(int i = 0; i < n; i++) { cin>>data; AddToTail(list,data); } } pNode FindNode(List list,int data) { if(list == NULL) { return NULL; } pNode pTemp = list; while(pTemp != NULL) { if(pTemp->data == data) { return pTemp; } pTemp = pTemp->next; } return NULL; } void Traverse(List list) { pNode pTemp = list; while(pTemp != NULL) { cout<<pTemp->data<<" "; pTemp = pTemp->next; } cout<<endl; } //在O(1)时间删除结点。注:必须保证pDel为链表中的结点 void DeleteNode(List *list,pNode pDel) { if(*list == NULL || pDel == NULL) { return; } //不是最后一个节点 if(pDel->next != NULL) {//复制pDel后边的结点的值,并删除pDel后边的结点 pNode pTemp = pDel->next; pDel->data = pTemp->data; pDel->next = pTemp->next; free(pTemp); pTemp = NULL; }else if(*list == pDel)//链表仅有一个结点 { free(pDel); pDel = *list = NULL; }else//是最后一个结点 { pNode pTemp = *list; while(pTemp->next != pDel) { pTemp = pTemp->next; } pTemp->next = NULL; free(pDel); pDel = NULL; } } int main() { List list = NULL; int n; cin>>n; Create(&list,n); Traverse(list); int data; cin>>data; pNode p = FindNode(list,data); if(p != NULL) { DeleteNode(&list,p); } Traverse(list); return 0; }
在O(1)时间内删除单向链表结点,布布扣,bubuko.com
标签:style os io 2014 for re c 代码
原文地址:http://blog.csdn.net/chdjj/article/details/38112095