您的位置:首页 > 其它

每天一个小算法(4)----在O(1)时间删除指定结点

2014-06-13 14:43 330 查看
O(1)时间内删除结点的思路只能是复制该结点下一个结点的数据,然后删除该结点的下一个结点,来等效删除此结点。

需要注意的地方是删除头结点和尾结点的处理。

#include <stdio.h>
#include <time.h>
#include <stdlib.h>
typedef struct Node
{
int data;
Node* next;
}Node, *List;

List createList(int num) //随机生成数字,构造链表
{
List aList = (List)malloc(sizeof(Node));
aList->next = NULL;
aList->data = 0;
Node* qT = aList;

// srand((int)time(0));
for ( int i=0; i< num; ++i)
{
Node* pTN = (Node*)malloc(sizeof(Node));
pTN->data = rand()%100;
pTN->next = NULL;
qT->next = pTN;
qT = pTN;
}
return aList;
}

void printList(List aList)    //打印链表
{
if ( aList == NULL || aList->next == NULL )
return;

Node* pT = aList->next;
printf("element of list:\n\t");
while( pT != NULL )
{
printf("%d ", pT->data);
pT = pT->next;
}

printf("\n");
}

void deleteList(List aList)    //删除链表
{}

//删除结点主算法
void deleteNode(List aList, Node* pNode)
{
if ( aList == NULL || pNode == NULL )
return;

if ( aList == pNode )
{
printf("refuse to delete head node\n");
return;
}

if ( pNode->next == NULL )
{
Node* pT = aList->next;
while ( pT->next != NULL )
{
pT = pT->next;
}

delete pNode;
pT->next == NULL;
}

Node* pN = pNode->next;
pNode->data = pNode->next->data;
pNode->next = pNode->next->next;

delete pN;
}

int main(int argc, char const *argv[])
{
srand((int)time(0));
List aList = createList(5);
printList(aList);
deleteNode(aList,aList->next->next);
printList(aList);
deleteList(aList);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐