删除一个无头单链表的非尾节点

来源:互联网 发布:2017网络视听大会 编辑:程序博客网 时间:2024/06/05 06:44
#define _CRT_SECURE_NO_WARNINGS 1//删除一个无头单链表的非尾节点#include<iostream>#include<stdlib.h>using namespace std;typedef int DataType;typedef struct SListNode{DataType data;            //数据struct SListNode* next;   //指向下一个结点的指针}SListNode;SListNode* CreateNode(DataType x)  //创造结点{//1.先开辟空间 2.数据赋给data 3.指针置空SListNode* NewNode = (SListNode*)malloc(sizeof(SListNode));NewNode->data = x;NewNode->next = NULL;return NewNode;}void PushBack(SListNode* &ppHead, int Data){//1.none 2.one and moreif (ppHead == NULL){ppHead = CreateNode(Data);}else{//1.先找到尾结点 2.把新节点链起来SListNode* cur = ppHead;while (cur->next){cur = cur->next;}cur->next = CreateNode(Data);}}//删除一个无头单链表的非尾节点void DelNoHeadNotTail(SListNode* &ppHead ,  int pos){if (ppHead == NULL)  //边界条件检查return;else{SListNode* prev = ppHead; //prev指向要删除结点的前一个结点SListNode* cur = prev->next; //cur指向要删除节点while (cur->data!= pos){cur = cur->next;prev = prev->next;}prev->next = cur->next;free(cur);cur->next = NULL;}}void PrintSNodeList(SListNode*&ppHead){while (ppHead){printf("%d->", ppHead->data);ppHead = ppHead->next;}cout << "NULL";printf("\n");}void Test(){SListNode* pHead = NULL;PushBack(pHead, 1);PushBack(pHead, 2);PushBack(pHead, 3);PushBack(pHead, 4);PushBack(pHead, 5);DelNoHeadNotTail(pHead, 2);PrintSNodeList(pHead);}int main(){Test();system("pause");return 0;}


1 0
原创粉丝点击