链表基本操作

  2020-3-14 


建输增删查改反

#include <stdio.h>
// null head node
struct node
{
	int content;
	struct node *next;
};
struct node *createLinklist()
{
	struct node *head = malloc(sizeof(struct node));  
	struct node *p = head;
    int input=-1;
	while(input!=0)
	{
		scanf("%d",&input);
		struct node *new = malloc(sizeof(struct node));
		new->content = input;
		new->next = NULL;
		p->next = new;
		p = p->next;
	}
	p->next=NULL;
	return head;
}

void printLinkList(struct node *head)
{
	struct node *p = head->next;
	while(p->next!=NULL)
	{
		printf("%d ",p->content);
		p = p->next;
	}
	printf("\n");
}

void reversePrintLinkList(struct node *head)
{
	// 递归出入口
	if (head->next!=NULL)
		reversePrintLinkList(head->next);
	//递归执行体
	printf("%d ",head->content); 
}

void deleteNode(struct node *head,int label)
{
	struct node *p = head;
	int i;
	for(i=0; i<label-1;i++)
	{
		p = p->next;
	}
	p->next = p->next->next;
}

void addNode(struct node *head,int label,int content)
{
	struct node *p = head;
	int i;
	for (i=0; i<label;i++)
	{
		p = p->next;
	}
	struct node *new = malloc(sizeof(struct node));
	new->content = content;
	new->next = p->next;
	p->next = new;
}

int findNode(struct node *head,int content)
{
	struct node *p = head->next;
	int count = 1;
	do
	{
		if (p->content == content)
			return count;
		else
			{
				count+=1;
				p = p->next;
			}
	}while(p->next!=NULL);
	return -1;
}

int main()
{	
	struct node *LinkList = createLinklist();
	printLinkList(LinkList); 
	
//	printf("which one to delete?\n");
//	int label;
//	scanf("%d",&label);
//	deleteNode(LinkList,label);
//	printLinkList(LinkList);

//	printf("where to add behind and what?\n");
//	int label,content;
//	scanf("%d %d",&label,&content);
//	addNode(LinkList,label,content);
//	printLinkList(LinkList);

//	printf("what content to find?\n");
//	int content;
//	scanf("%d",&content);
//	printf("found it in position %d",findNode(LinkList,content));

	printf("start reversing...\n");
	reversePrintLinkList(LinkList->next);
	printf("\n");
	
    return 0;
} 

且听风吟