链表操作

来源:互联网 发布:苏沉船 王晶 知乎 编辑:程序博客网 时间:2024/06/01 16:36
////////////单链表/////////////////定义节点struct node{int data;    struct node *next;};typedef struct node NODE;//申请节点并赋值NODE *ApplyNODE(int x){NODE *p;p=(NODE *)malloc(sizeof(NODE));p->data=x;p->next=NULL;        return (p);}//初始化链表NODE *InitList(){NODE *head;head=(NODE *)malloc(sizeof(NODE));head->next=NULL;return (head);}//将节点插入到链表//(1)将节点p插入到链表头(p作为head之后的第一个元素,成为了新的表头节点)p->next=head->next;head->next=p;//(2)将节点p插入到指定节点q之后p->next=q->next;q->next=p;//(3)将节点p插入到链表尾先找到链表的尾节点q:NODE *Searchrear(NODE *head){NODE *q;q=head;while(q->next != NULL){q=q->next;}return (q);}再将p节点插入到指定节点q的后面即可!//头插法建立链表NODE *CreateFromHead(){NODE *head, *p, *q;int i, n, x;printf("\nInput the length of the line:");scanf("%d", &n);head=InitList();printf("\nInput %d datas:", n);for(i=0; i<n; i++){scanf("%d", &x);p=applyNODE(x);p->next=head->next;head->next=p;}return (head);}//尾插法建立链表NODE *CreatFromTail(){NODE *head, *p, *q;int i, n, x;printf("\nInput the length of the line :");scanf("%d", &n);head=q=InitList();printf("\nInput %d datas:", n);for(i=0; i<n; i++){scanf("%d", &x);p=applyNODE(x);q->next=p;q=p;}return (head);}//删除节点//(1)删除给定节点p的后继节点, 用q记录要删除的节点q=p->next;p->next=q->next;free(q); //(2)删除给定节点pNODE *deletenode(NODE *head, NODE *p){NODE *q;q=head;while(q->next != p){q=q->next;}q->next=p->next;free(p);return (head);}//输出单链表void Display(NODE *head){NODE *p;printf("\nThe line are:");p=head->next;while(p != NULL){printf("%d ", p->data);p=p->next;}}//查找给定值节点NODE *Search(NODE *head, int x){NODE *p;p=head->next;while(p != NULL)&&(p->data != x){p=p->next;}    return (p);}////////////链表实现栈/////////////////栈节点struct node{int data;struct node *next;};typedef struct node StackNode;StackNode *top;//初始化栈StackNode *InitStack(){NODE *top;top=(StackNode *)malloc(sizeof(StackNode));top->next=NULL;return (top);}//将x进栈StackNode *Push(StackNode *top, DataType x){StackNode *p;p=(StackNode *)malloc(sizeof(StackNode));p->data=x;p->next=top->next;top->next=p;return (top);}//将栈顶元素出栈StackNode *Pop(StackNode *top){StackNode *p;if(top->next == NULL){printf(" 栈空,无法出栈");return(top);}p=top->next;top->next=p->next;free(p);return (top);}////////////链表实现队列/////////////////链队列节点struct node{    int data;struct node *next;};typedef struct node QueueNode;struct node2{QueueNode *front;QueueNode *rear;};typedef struct node2 Queue;//初始化队列Queue InitQueue(){Queue Q;Q.front=(QueueNode *)malloc(sizeof(QueueNode));Q.front->next=NULL;Q.rear=Q.front;return (Q);}//x进队列Queue InsertQ(Queue Q, int x){QueueNode *p;p=(QueueNode *)malloc(sizeof(QueueNode));p->data=x;p->next=NULL;Q.rear->next=p;Q.rear=p;    return (Q);}//出队列Queue DeleteQ(Queue Q){QueueNode *p;if(Q.front == Q.rear){printf("队列空,无法出队列!");return (Q);}p=Q.front->next;Q.front->next=p->next;if(p==Q.rear){Q.rear=Q.front;}free(p);return (Q);}


0 0