风之城的单链表
#include <iostream>
#include "stdlib.h"
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;
}
}
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);
}
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;
}
*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);
printList(head);
return 0;
}