您的位置:首页 > 编程语言

编程之美—从无头链表中删除结点

2014-06-04 10:33 239 查看
一个无头单链表中,一个指针指向此单链表中间的一个结点(不是第一个结点,也不是尾结点),请将该结点删除。

思想: 在不知道第一结点情况下,这个问题看起来无从下手。但是我们知道要删除结点的信息,以及要删除结点的下一结点信息以及下下个结点信息。 知道这些,我们可以知道可以较容易删除要删除结点的下一结点。如何将问题转换呢?只需将要删除结点的数据和要删除结点的下一结点的数据交换皆可。

代码如下:

// NoHeadList.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>

using namespace std;
typedef int type;

//单链表结点
typedef struct node
{
	type data;
	struct node *next;
}node,*pNode;

//创建无头结点单链表
void CreateList(pNode &L,type *a,int n)
{
	L=(pNode)malloc(sizeof(node));
	if(NULL==L)
	{
	  cout<<"申请内存失败!"<<endl;
	  exit(-1);
	}
	L->data=a[0];
	L->next=NULL; 
	pNode p=L;

	for(int i=1;i<n;i++)
	{
	  pNode temp=(pNode)malloc(sizeof(node));
	  if(NULL==temp)
	  {
	     cout<<"申请内存失败!"<<endl;
	      exit(-1);
	  }
	  temp->data=a[i];
	  temp->next=NULL;
	  p->next=temp;
	  p=temp;
	}

}
//打印单链表
void PrintList(pNode L)
{
	pNode temp=L;
	while(NULL!=temp)
	{
		cout<<temp->data<<" ";
		temp=temp->next;
	}
	cout<<endl;

}
//计算单链表长度
int Len(pNode L)
{
     int i=0;
	 pNode temp=L;
	 while(NULL!=temp)
	 {
	   i++;
	   temp=temp->next;
	 }
	 return i;
}
//取出单链表中某一结点
pNode GetNode(int i,pNode L)
{
	 int len=Len(L);
	 if((i<1)||(i>len))
	 {
	  cout<<"越界!"<<endl;
	  exit(-1);
	 }
	 pNode temp=L;
	 
	 for(int j=i-1;j>0;j--)
	 {
		 temp=temp->next;
	 }
	 return temp;
}

//删除无头结点单链表中的某一点   无法知道第一结点位置,只知道要删除的结点(不是第一结点,也不是尾结点)
type DeleteNode(pNode p)
{
	type ch=p->data;
	pNode temp=p->next;   
	p->data=temp->data; 
	p->next=temp->next;
	return ch;
}

int _tmain(int argc, _TCHAR* argv[])
{
	type a[6]={10,11,12,13,14,15};
	pNode L=NULL;
	CreateList(L,a,6);
	PrintList(L);

	pNode tp=GetNode(3,L);//取一个要删除的结点  模拟出随机指向单链表一个结点的指针
	DeleteNode(tp);
	PrintList(L);
	return 0;
}


结果:

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