码迷,mamicode.com
首页 > 其他好文 > 详细

给定单向链表的头指针和一个结点指针,定义一个函数在O(1)时间删除该结点

时间:2014-06-27 23:54:36      阅读:311      评论:0      收藏:0      [点我收藏+]

标签:o1时间删除链表结点

#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 = toDeleteNode->data;
		toDeleteNode->data = (toDeleteNode->next)->data;
		(toDeleteNode->next)->data = tmpData;
		tmp = toDeleteNode->next;
		toDeleteNode->next = (toDeleteNode->next)->next;
		delete tmp;
		return head;
	}
	
	//不止一个结点,要删除的结点是尾结点
	while (tmp->next)
	{
		tmp = tmp->next;
		pre = pre->next;
	}
	pre->next = NULL;
	delete tmp;
	return head;
}

int main()
{
	struct Node *head = create_list(5);	
	visit(head);
	cout << endl;
	
	//删除头结点
	head = DeleteNode(head, head);
	visit(head);
	cout << endl;
	//删除尾结点
	struct Node* tmp = head;
	while (tmp->next)
		tmp = tmp->next;
	head = DeleteNode(head, tmp);	 
	visit(head);
	cout << endl;
	//删除第2个结点
	int num = 0;
	tmp = head;
	while (tmp->next)
	{
		num++;
		if (num == 2)
			break;
		tmp = tmp->next;	
	}
	head = DeleteNode(head, tmp);
	visit(head);
	cout << endl;
	free_list(head);
	return 0;
}


给定单向链表的头指针和一个结点指针,定义一个函数在O(1)时间删除该结点,布布扣,bubuko.com

给定单向链表的头指针和一个结点指针,定义一个函数在O(1)时间删除该结点

标签:o1时间删除链表结点

原文地址:http://blog.csdn.net/aspnet_lyc/article/details/35271523

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!