Demo entry 6628137

1323

   

Submitted by 12321 on Jul 01, 2017 at 12:05
Language: C++. Code size: 1.6 kB.

#include "stdafx.h"
#include "stdlib.h"
#include "stdio.h"
#define NULL 0
typedef int ElemType;
struct ListNode
{
	ElemType data;
	ListNode *pNext;
};
typedef ListNode* ListLink;
ListLink Create()
{
	ListNode* head=(ListNode*)malloc(sizeof(ListNode));
	head->pNext=NULL;
	return head;
}
bool ListInsert(ListLink& L,int i,ElemType e)
{
	ListLink pCur=L;
	int j=0;
	while(pCur!=NULL && j<i-1)
	{
		pCur=pCur->pNext;
		++j;
	}
	if(pCur==NULL||j>i-1)
		return false;
	ListLink s=(ListNode*)malloc(sizeof(ListNode));
	s->data=e;
	s->pNext=pCur->pNext;
	pCur->pNext=s;
	return true;
}
void printint(ElemType a)
{
	printf("%d\n",a);
}
void TravelLink(ListLink& L,void(*print)(ElemType))
{
	ListLink pCur=L->pNext;
	while(pCur!=NULL)
	{
		(*print)(pCur->data);
		pCur=pCur->pNext;
	}
}
bool ListDelete(ListLink& L,int i,ElemType& e)
{
	ListLink pCur=L;
	int j=0;
	while(pCur!=NULL && j<i-1)
	{
		pCur=pCur->pNext;
		++j;
	}
	if(pCur->pNext==NULL||j>i-1)
		return false;
	ListLink q=pCur->pNext;
	pCur->pNext=q->pNext;
	e=q->data;
	free(q);
	return true;
}
void DestroyLink(ListLink& L)
{
	ListLink pCur=L,q;
	while(pCur!=NULL)
	{
		q=pCur;
		pCur=pCur->pNext;
		free(q);	
	}
}
int main(int argc, char* argv[])
{
	int i,v;
	ListLink head=Create();
	for(i=1;i<=10;i++)
		ListInsert(head,i,i*10);
	TravelLink(head,printint);
	ListDelete(head,3,v);

	printf("Data Deleted:%d\n",v);
	ListDelete(head,8,v);
	printf("Data Deleted:%d\n",v);
	TravelLink(head,printint);
	DestroyLink(head);
	return 0;
}

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).