/************************************** *函数功能:给定头结点和当前结点,删除当前结点 *复杂度:O(1) *说明:谷歌广为流传的面试题,根据相关思路自己 实现的代码 *思路:教科书上删除当前结点都使用遍历,复杂度是 O(n),不妨换个思路,使用当前结点的下一个结点替换 当前结点的内容,然后删掉下一个结点。 **************************************/ #include <stdio.h> #include <malloc.h> typedef int Datatype; typedef struct Node { Datatype data; struct Node *next; } *linklist; linklist CreateList(); void DeleteNode(linklist phead, linklist pToBeDelete ); int main() { linklist phead = CreateList(); linklist p = phead; //未删除结点时 while(p->next != NULL) { printf("%c", p->data); p = p->next; } printf("%c\n", p->data); //假设删除的时最后的一个结点 DeleteNode(phead, phead->next); p = phead; //删除结点后 while(p->next != NULL) { printf("%c", p->data); p = p->next; } printf("%c\n", p->data); return 0; } //头插法建表 linklist CreateList() { char ch; linklist phead,ps; phead = NULL; ch = getchar(); while(ch != '$') { ps = malloc(sizeof(struct Node)); ps->data = ch; ps->next = phead; phead = ps; ch = getchar(); } return phead; } //删除指定结点,考虑指定结点为最后一个结点 void DeleteNode(linklist phead, linklist pToBeDelete ) { linklist pNext = pToBeDelete->next; if(pNext != NULL) { pToBeDelete->data = pNext->data; pToBeDelete->next = pNext->next; free(pNext); } else { while(phead->next != pToBeDelete) { phead = phead->next; } free(pToBeDelete); phead->next = NULL; } }
谷歌面试题:给定头结点和当前结点,删除当前结点
最新推荐文章于 2022-05-03 17:38:05 发布