链表的创建、插入、打印、删除C语言执行

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

struct Student{
	char cName[20];
	int iNumber;
	struct Student* pNext;
};

int iCount = 0;

//创建链表
struct Student* Create( ){
	struct Student* pHead = NULL;
	struct Student* pNew = NULL;
	struct Student* pEnd = NULL;
	printf( "Please input the name then the number:\n" );
	pEnd = pNew = (struct Student*)malloc(sizeof(struct Student));
	scanf( "%s%d", pNew->cName, &pNew->iNumber );
	while( 1 ){
		iCount++;
		if( 1 == iCount ){
			pNew->pNext = NULL;
			pEnd = pNew;
			pHead = pNew;
		}
		else{
			pNew->pNext = NULL;
			pEnd->pNext = pNew;
			pEnd = pNew;
		}
		pNew = (struct Student*)malloc( sizeof( struct Student));
		scanf( "%s", pNew->cName );
		if( strcmp(( pNew->cName), "exit") == 0 ){
			break;
		}
		scanf( "%d", &pNew->iNumber );
	}
	free( pNew );
	return pHead;
};

//打印链表
void Print( struct Student* pHead ){
	struct Student* pTemp = pHead;
	while( pTemp != NULL ){
		printf( "%s %d\n", pTemp->cName, pTemp->iNumber );
		pTemp = pTemp->pNext;
	}
}

//插入链表
struct Student* Insert( struct Student* pHead ){
	printf( "------Insert Node------\n" );
	struct Student* pTemp = pHead;
	struct Student* pPre = pHead;
	struct Student* pInsert = NULL;
	printf( "请输入要插入的节点的名字和工号:\n" );
	pInsert = (struct Student* )malloc( sizeof( struct Student) );
	scanf( "%s%d", pInsert->cName, &pInsert->iNumber );
	printf( "%s%d", pInsert->cName, pInsert->iNumber );
	printf( "请输入要插入的节点:\n");
	int iIndex;
	scanf( "%d", &iIndex );
	if( 1 == iIndex ){
		pInsert->pNext = pHead;
		pHead = pInsert;
		iCount++;
	}
	else{
		int i;
		for( i=1; i<iIndex; i++ ){
			pPre = pTemp;
			pTemp = pTemp->pNext;	
		}
		pInsert->pNext = pTemp;
		pPre->pNext = pInsert;
		iCount++;
	}
	return pHead;
};

//删除链表
struct Student* Delete( struct Student* pHead ){
	struct Student* pTemp = pHead;
	struct Student* pPre = pHead;
	printf( "------Delete Node------\n" );
	printf( "请输入删除的第几个节点:\n");
	int iIndex;
	scanf( "%d", &iIndex );
	if( 1 == iIndex ){
		pTemp = pTemp->pNext;
		free( pHead );
		pHead = pTemp;
		iCount++;
	}
	else{
		int i;
		for( i=1; i<iIndex; i++ ){
			pPre = pTemp;
			pTemp = pTemp->pNext;
		}
		pPre->pNext = pTemp->pNext;
		iCount--;
	}
	return pHead;
};


int main( ){
	struct Student* pHead;
	//链表的创建
	pHead = Create();
	//链表的打印
	Print( pHead);
	//链表的插入
	pHead = Insert(pHead);
	//链表的打印
	Print( pHead);
	//链表的删除
	pHead = Delete( pHead );
	//链表的打印
	Print( pHead );
	return 0;
}

  

posted on 2023-07-18 14:53  笛若心生  阅读(116)  评论(0)    收藏  举报

导航