C语言单向链表的各种操作

直接上代码了。

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

#include "stdafx.h"
#include<stdio.h>
#include<stdlib.h>    //malloc函数
using namespace std;


typedef int dataType;
typedef struct ListNode {
	dataType data;
	ListNode* next;
}Node,*PNode;
//创建链表
PNode createList() {
	PNode head = (PNode)malloc(sizeof(Node));
	if (head == NULL) {
		printf("分配地址失败!\n");
		exit(-1);
	}
	int Nodenum;
	printf("请输入节点的个数:");
	scanf_s("%d", &Nodenum);
	PNode tail = head;
	tail->next = NULL;
	for (int i = 0; i < Nodenum; i++) {
		PNode newNode = (PNode)malloc(sizeof(Node));
		if (newNode == NULL) {
			printf("新分配地址失败!");
			exit(-1);
		}
		int val;
		printf("请输入第%d节点的数据:",i+1);
		scanf_s("%d", &val);
		newNode->data = val;
		newNode->next = NULL;
		tail->next = newNode;
		tail = newNode;
	}
	printf("链表创建成功!\n");
	return head;
}

//输出链表
void printLink(PNode head) {
	if (head->next == NULL) {
		printf("链表为空!\n");
		exit(-1);
	}
	PNode p= head->next;
	while (p != NULL) {
		printf("节点数据是:%d--->", p->data);
		p = p->next;
	}
	printf("\n");
}

//将数据插入链表

//辅助函数,新建一个节点
PNode createNewNode(dataType data) {
	PNode newNode = (PNode)malloc(sizeof(Node));
	if (newNode == NULL) {
		printf("新分配地址失败!");
		exit(-1);
	}
	newNode->data = data;
	newNode->next = NULL;
	return newNode;
}

//头插法
PNode headInsertNode(PNode head,dataType data) {
	PNode newNode = createNewNode(data);
	newNode->next = head->next;
	head->next = newNode;
	return head;

}

//尾插法
void tailInsertNode(PNode head, dataType data) {
	PNode newNode = createNewNode(data);
	PNode tail = head;
	while (tail->next != NULL) {
		tail = tail->next;
	}
	tail->next = newNode;
}

//删除指定的节点
void deleteNode(PNode head,dataType data) {
	if (head->next == NULL) {
		printf("链表为空!");
		exit(-1);
	}
	PNode p1 = head;
	PNode p2 = head->next;
	while (p2->data != data && p2 != NULL) {
		p1 = p2;
		p2 = p2->next;
	}
	if (p2 == NULL) {
		printf("%d不在链表中", data);
		exit(-1);
	}
	p1->next = p2->next;
	free(p2);
}

//查找指定的元素的位置
int searchNode(PNode head, dataType data) {
	if (head->next == NULL) {
		printf("链表为空!");
		exit(-1);
	}
	PNode p1 = head;
	PNode p2 = head->next;
	int Index = 1;
	while (p2->data != data && p2 != NULL) {
		p1 = p2;
		p2 = p2->next;
		Index++;
	}
	if (p2 == NULL) {
		printf("%d不在链表中", data);
		exit(-1);
	}
	return Index;
}

//删除整个链表
void deleteLink(PNode head) {
	if (head->next == NULL) {
		printf("链表为空!");
		exit(-1);
	}
	PNode tmp, p = head->next;
	while (p != NULL) {
		tmp = p->next;
		free(p);
		p = tmp;
	}
	head->next = NULL;
}



int main()
{
	PNode head = createList();
	printLink(head);
	//head=headInsertNode(head, 40);
	//tailInsertNode(head,40);
	//deleteNode(head, 30);
	//tailInsertNode(head, 50);
	//printLink(head);
	//printf("%d在第%d个节点!\n", 10, searchNode(head, 10));
	deleteLink(head);
	printLink(head);
	return 0;
}


猜你喜欢

转载自blog.csdn.net/xwm1993/article/details/80409041