首页 > 代码库 > 给定单向链表的头指针和一个结点指针,定义一个函数在O(1)时间删除该结点
给定单向链表的头指针和一个结点指针,定义一个函数在O(1)时间删除该结点
#include <iostream> #include <string.h> #include <stdlib.h> #include <stack> using namespace std; struct Node { int data; struct Node* next; }; struct Node* create_list(int len) { if (len <= 0) return NULL; struct Node* head; struct Node* tmp; struct Node* pre; for (int i=0; i<len; i++) { if (i == 0) { head = tmp = new struct Node; cin >> tmp->data; tmp->next = NULL; pre = tmp; continue; } tmp = new struct Node; cin >> tmp->data; tmp->next = NULL; pre->next = tmp; pre = tmp; } return head; } void visit(const struct Node *head) { if (head == NULL) return; const struct Node *tmp; tmp = head; while (tmp) { cout << tmp->data; tmp = tmp->next; } } void free_list(struct Node *head) { if (head == NULL) return; struct Node *tmp; while (head) { tmp = head; head = head->next; delete tmp; } } struct Node* DeleteNode(struct Node *head, struct Node *toDeleteNode) { if (!head || !toDeleteNode) return NULL; struct Node* tmp = head->next; struct Node* pre = head; if (head == toDeleteNode) { delete head; return tmp; } //要删除的结点不是尾结点 if (toDeleteNode->next) { int tmpData = http://www.mamicode.com/toDeleteNode->data;>
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。