单链表的操作

Talk is cheap, show the code

#include <stdio.h>
#include <stdlib.h>
#define ERROR -404

typedef struct Node {
	int data;
	struct Node* next;
} Node;

Node* InitList (void);
void add_front (Node* head,int data);
void add_back (Node* head, int data);
void PrintList (Node* head);
int Length (Node* head);
int Get (Node* head, int l); //按位查找 
int Locate (Node* head, int n); //按值查找 
void Insert (Node* head, int i, int x);
void Delete (Node* head, int i);
void FreeL (Node* head);

int main ()
{
	Node* head= InitList();
	int num =1,i,x;
	scanf("%d",&num);
	while (num!= -1) {
		add_front(head,num);
		scanf("%d",&num);
	}
	PrintList(head);
	printf("The length is %d\n",Length(head));
	scanf("%d",&i);
	printf("Get: %d\n",Get(head,i));
	PrintList (head);
	scanf("%d",&i);
	printf("Locate: %d\n",Locate(head,i));
	PrintList (head);
	scanf("%d %d",&i,&x);
	Insert(head,i,x);
	PrintList (head);
	scanf("%d",&i);
	Delete(head,i);
	PrintList (head);
	FreeL(head);
	return 0;
}

Node* InitList (void)
{
	Node* head = (Node*)malloc(sizeof(Node));
	head ->next = NULL; // 设置哨兵节点 mark
	return head;
}
// 强行尾插,要尾插建议加入尾指针 
void add_back(Node* head, int data) {
	Node *p,*end=head,*q;
	for ( p=head; p ; p=p->next) {
		end =p;
	}
	q =(Node*)malloc(sizeof(Node));
	end->next =q;
	q->data =data;
	q->next= NULL;
	return ;
}

void add_front(Node* head, int data) {
	Node *p = (Node *)malloc(sizeof(Node));
	p -> next = head -> next;
	head -> next = p;
	p -> data = data;
	return ;
}
void PrintList (Node* head) 
{
	Node* p;
	for (p =head->next; p; p=p->next) {
		printf("%d ",p->data);
	}	
	printf("\n");
}

int Length (Node* head)
{
	Node* p;
	int sum=0;
	for (p=head->next; p; p=p->next) {
		sum++;
	}
	return sum;
}

int Get (Node* head, int l) // 按位查找 
{
	Node* p;
	int cnt=0;
	for (p=head->next; p ; p=p->next) {
		cnt++;
		if (cnt==l) {
			return p->data;
			break;
		}
	}
	return ERROR;
} 

int Locate (Node* head, int n)
{
	Node* p;
	int cnt=0;
	for (p=head->next ; p; p=p->next) {
		cnt++;
		if (p->data == n) {
			return cnt;
		}
	} 
	return ERROR;
} 

void Insert (Node* head, int i, int x) {
	Node *p,*q,*r;
	int cnt=0;
	for (p=head->next,q=head; q; q=p,p=p->next) {
		cnt++;
		if (cnt==i) {
			r=(Node*)malloc(sizeof(Node));
			r->data =x;
			r->next =p;
			q->next =r;
			return ;
		} 
	}
	printf("ERROR\n");
}

void Delete (Node* head, int i) 
{
	int cnt=0;
	Node *p,*q;
	for (p=head->next,q=head; p; q=p, p=p->next) {
		cnt ++;
		if (cnt==i) {
			q->next= p->next;
			free(p);
			return ;
		}
	}
	printf("ERROR\n");
}

void FreeL (Node* head) 
{
	Node *p,*q;
	for (p=head->next, q=head; p; q=p, p=p->next) {
		free(q);
	}
	free(q);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值