编程之美—从无头链表中删除结点
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; }
结果:
相关文章推荐
- 编程之美--从无头链表中删除结点
- <笔试><面试>单链表相关(1)从尾到头打印链表、删除一个无头链表的非尾结点
- 3.4——从无头单链表中删除结点
- 《编程之美》3.4:没有头结点的单链表如何删除结点
- 单链表的建立(头部延长、尾部延长)、插入操作、删除操作(无头结点的删除、有头结点的删除)
- 面试题:从无头链表中删除已知结点
- 编程之美:第三章 结构之法 3.4从无头单链表中删除节点
- 编程之美:从无头单链表中删除节点
- 假设在长度大于1的循环链表中,即无头结点也无头指针,s为指向链表中的某个结点的指针,试编写算法删除结点s的前驱结点
- 单链表中头结点的有无. 并讨论下有无头结点在单链表的创建,打印,插入,逆置,删除中的区别.
- 每日一刷——删除无头链表非尾结点&倒序打印链表
- 【编程之美】从无头单链表中删除结点
- 编程之美——从无头单链表中删除节点
- 从无头单链表中删除某节点(编程之美3.4)
- 编程之美:从无头单链表中删除节点,讨论
- <笔试><面试>单链表相关(1)从尾到头打印链表、删除一个无头链表的非尾结点
- 编程之美:从无头单链表中删除节点,讨论
- 链表面试题(一)---删除一个无头单链表的非尾结点
- 面试题 单向链表(无头结点)一个指针指向其中的一个结点,如何删除这个结点?
- 链表之无头指针删除单链表指定结点