前言:利用鏈結串列製作Stack和Queue


#include<stdio.h>
#include<string.h>
#define A_No 1
#define Z_No 26

struct node{

int data;

struct node *next;

};


int countList(struct node *head);
void reverseList(struct node **head);
void printList(struct node *head);
void updateList(struct node *head);
void push(struct node **top,struct node *newNode);
void pop(struct node **top);
void insertQueue(struct node **front,struct node **rear,struct node *newNode);
void deleteQueue(struct node **front,struct node **rear);

int main(void)
{

struct node *top=NULL;

struct node *front=NULL;

struct node *rear=NULL;

struct node A={1,NULL};

struct node B={2,NULL};

struct node C={3,NULL};

struct node D={4,NULL};

struct node newNode={10,NULL};

struct node newNode1={20,NULL};


front=&D;

rear=&A;

top=&D;

D.next=&C;

C.next=&B;

B.next=&A;

A.next=NULL;

printList(top);

push(&top,&newNode);

printList(top);

pop(&top);

printList(top);

insertQueue(&front,&rear,&newNode1);

printList(front);

deleteQueue(&front,&rear);

printList(front);

return 0;
}


void push(struct node **top,struct node *newNode)
{

if(*top==NULL){

*top=newNode;

(*top)->next=NULL;

}else{

newNode->next=*top;

*top=newNode;

}

}

void pop(struct node **top)
{

if(*top==NULL)

printf("stack is empty.\n");

else if((*top)->next==NULL){

printf("pop out data:%d\n",(*top)->data);

*top=NULL;

}else{

printf("pop out data:%d\n",(*top)->data);

*top=(*top)->next;

}

}

void insertQueue(struct node **front,struct node **rear,struct node *newNode)
{

if(*front==NULL && *rear==NULL){

*front=newNode;

*rear=newNode;

(*rear)->next=NULL;

}else{

(*rear)->next=newNode;

*rear=newNode;

(*rear)->next=NULL;

}

}

void deleteQueue(struct node **front,struct node **rear)
{

if(*front==NULL && *rear==NULL)

printf("Queue is empty.\n");

else if(*front==NULL){

printf("The data is:%d\n",(*front)->data);

*front==NULL;

*rear==NULL;

}else{

printf("The data is:%d\n",(*front)->data);

*front=(*front)->next;

*rear=(*rear)->next;

}

}

void printList(struct node *head)
{

struct node *P=head;


if(P==NULL){

printf("stack is empty.\n");

return;

}

printf("Linked List data:");

while(1)

{

printf("%d",P->data);

if(P->next==NULL)

{

printf("\n");

break;

}

else

{

P=P->next;

printf("->");

}

}

}

int countList(struct node *head)
{

int listcount=1;

struct node *P=head;

while(P->next!=NULL)

{

listcount++;

P=P->next;

}

return (listcount);
}

void reverseList(struct node **head)
{

struct node *p=*head;

struct node *q=*head;


p=p->next;

q->next=NULL;


while(p!=NULL)

{

q=p;

p=p->next;

q->next=*head;

*head=q;

}

}

void updateList(struct node *head)
{

struct node *P=head;

while(1)

{

P->data=(P->data==A_No)?Z_No:P->data;

if(P->next!=NULL)

P=P->next;

else

break;

}

}


arrow
arrow
    全站熱搜
    創作者介紹
    創作者 GavinHuang 的頭像
    GavinHuang

    Gavin的部落格

    GavinHuang 發表在 痞客邦 留言(0) 人氣()