单链表的前7个操作哦

风之城的单链表

#include <iostream>
#include "stdlib.h"

//Node结构体 
struct Node{
	int data;
	struct Node *next;
}; 

//从头部添加新节点,新节点变为新的头部 
void push(Node **head, int data)
{
	
	Node *new_node = (Node*) malloc(sizeof(Node));
	
	new_node->data = data;
	new_node->next = (*head);
	(*head) = new_node;
	
}

//从尾部添加新节点 
void append(Node **head,int data)
{
	Node *temp = *head; 
	if(temp ==NULL)
		return;
	
	while(temp->next != NULL)
	{
		 temp = temp->next;
	}
	Node *new_node = (Node*) malloc(sizeof(Node));
	new_node->data = data;	
	new_node->next = NULL;
	temp->next = new_node;
	
}

//打印链表 
void printList(Node *head)
{
	
	while(head != NULL)
	{
		printf("%d ->",head->data);
		head = head->next;
	}
	
}

//根据key值删除某个节点 
void deleteNodeByKey(Node **head, int key)
{
	Node *temp = *head;	
	//先判断头结点是否为空,为空则直接退出程序 
	if(temp == NULL)
		return;
	if(temp -> data == key)
	{
		*head = temp -> next;
		free(temp);
		return;
	}
	while(temp->next != NULL && temp->next->data != key)
	{
		temp = temp->next;
	}
	if(temp->next ==NULL)
	{
		printf("抱歉没有找到该key \n");
		return;
	}
	Node *keyNode = temp->next;
	temp->next = temp->next->next;
	free(keyNode);
} 

//根据位置删除某个节点 
/*
Example : 
Input: position = 1, Linked List = 8->2->3->1->7
Output: Linked List =  8->3->1->7

Input: position = 0, Linked List = 8->2->3->1->7
Output: Linked List = 2->3->1->7
*/ 
void deleteNodeByPos(struct Node **head, int position) 
{
	Node *temp = *head;	
	
	if(temp == NULL)
		return;
	if(position == 0){
		*head = temp -> next;
		free(temp);
		return;
	} 
	for(int i=1;i<position; i++)
	{
		if(temp->next != NULL){
			temp = temp->next;
		}else{
			return;
		}				
	}
	
	Node *keyNode = temp->next;
	temp->next = temp->next->next;
	free(keyNode);
	
} 

//删除一个链表
void deleteList(struct Node** head) 
{
	Node *temp = *head;
	Node *nextNode;
	if(*head == NULL)
		return;
	while(temp->next != NULL)
	{
	   nextNode=temp->next;
	   free(temp);
	   temp = nextNode;
	}
	
	//free完链表之后一定要将头指针置于空,不然打印的时候head将指向不明的位置,产生不可预料的结果 
	*head =NULL;
}

//获取链表的节点数目 
int getCount(Node* head) 
{
	Node *temp = head;
	int count=0;
	if(temp == NULL)
		return count;
	count++;
	while(temp->next != NULL){
		temp = temp->next;
		count++;
	}
	return count;
		
} 

int main()
{	
	Node *head = NULL;
	push(&head,10); 
	push(&head,8); 
	push(&head,5); 
	push(&head,6); 
	push(&head,12);	
	append(&head,13);
	
	int count = getCount(head); 
	printf("一共有%d个节点 \n",count); 
	
//	deleteNodeByKey(&head,13);
	//deleteNodeByPos(&head,2);
	
	//deleteList(&head);
	printList(head);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值