博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

单链表中删除节点(考虑尾节点情况,编程之美3.4)

Posted on 2010-09-22 15:42  KurtWang  阅读(6117)  评论(1编辑  收藏  举报
#include "stdafx.h"

struct Node
{
	int value;
	Node * next;
};

//不考虑删除节点为尾节点
void deleteNode(Node * pCurrent)
{
	if(pCurrent != NULL)
	{
		if(pCurrent->next != NULL)
		{
			Node * pTemp = pCurrent->next;
			pCurrent->value = pTemp->value;
			pCurrent->next = pTemp->next;
			delete pTemp;
		}
	}

}


//考虑删除节点为尾节点
void deleteNode2(Node * pCurrent, Node * head)
{
	if(pCurrent != NULL)
	{
		if(pCurrent->next != NULL)
		{
			Node * pTemp = pCurrent->next;
			pCurrent->value = pTemp->value;
			pCurrent->next = pTemp->next;
			delete pTemp;
		}
		else
		{
			Node * temp = head;
			while(temp != NULL)
			{
				if(temp->next == pCurrent)
				{
					delete pCurrent;
					temp->next = NULL;
				}
				temp = temp->next;
			}
		}
	}

}


int _tmain(int argc, _TCHAR* argv[])
{
	Node * n1 = new Node();
	Node * n2 = new Node();
	Node * n3 = new Node();
	n1->value = 1;
	n1->next = n2;
	n2->value = 2;
	n2->next = n3;
	n3->value = 3;
	n3->next = NULL;

	printf("before delete:");
	Node * temp = n1;
	while(temp!=NULL)
	{
		printf("%d ", temp->value);
		temp = temp->next;
	}

	printf("after delete:");
	deleteNode2(n3, n1);
	temp = n1;
	while(temp!=NULL)
	{
		printf("%d ", temp->value);
		temp = temp->next;
	}

	return 0;
}