链表(单链表有表头,双向链表只是多了个尾,具体实现差不多==就没写了)
以下为代码
声明?
#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
typedef int Element;
typedef struct List List;
struct List
{
int val;
struct List*next;
};
List* BuyListNode(Element x);
List* InitList();
void PrintList(List*phead);
void ListInsert(List*phead, Element x);//仅实现头插头删 修改
void ListDelete(List*phead);
void ListEdit(List*phead, Element x, Element InsertX);
List* Findpos(List*phead, Element x);//寻找节点是否存在;
代码
#include"List Stack.h"
//链表--只写了单链表,双链表差不多.
List* BuyListNode(Element x)
{
List*newnode = (List*)malloc(sizeof(List));
newnode->next = NULL; newnode->val = x;
return newnode;
}
List* InitList()
{
List*phead = BuyListNode(0);//建立哨兵节点
phead->next = NULL;
return phead;
}
void ListInsert(List*phead, Element x)//仅实现头插头删 修改
{
List*cur = phead->next;
List*newnode = BuyListNode(x);
phead->next = newnode;
newnode->next = cur;
}
void ListDelete(List*phead)
{
assert(phead);
List*cur = phead->next;
phead->next = phead->next->next;
free(cur);
}
void ListEdit(List*phead, Element x,Element InsertX)
{
List*cur = phead->next;
List* pos = Findpos(phead, x);
if (pos == NULL)
{
printf("无法找到\n");
return;
}
pos->val = InsertX;
}
List* Findpos(List*phead, Element x)//寻找节点是否存在
{
List*cur = phead->next;
while (cur)
{
if (cur->val == x)
{
return cur;
}
cur = cur->next;
}
return NULL;
}
void PrintList(List*phead)
{
List*cur = phead->next;
while (cur)
{
printf("%d ", cur->val);
cur = cur->next;
}
printf("\n");
}
栈的实现————相对来说更为简单,同样用了哨兵
声明
#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
typedef int Element;
struct Stack
{
int val;
struct Stack*next;
};
typedef struct Stack Stack;
Stack* CreatStack();
void PushStack(Stack* top, Element x);//入栈
void PopStack(Stack* top);//出栈
Element ReturnTopStack(Stack*top);//返回栈顶元素
void StackElementPrint(Stack*top);
代码
#include"List Stack.h"
//栈 ----实现 入栈,出栈,返回栈顶元素
Stack* CreatStack()
{
Stack* top = (Stack*)malloc(sizeof(Stack));//top非栈顶,为哨兵
top->next = NULL; top->val = 0;
return top;
}
void PushStack(Stack* top, Element x)//入栈
{
Stack* cur = (Stack*)malloc(sizeof(Stack));
cur->val = x;
cur->next = top->next;
top->next = cur;
}
void PopStack(Stack* top)//出栈
{
Stack* FirstCell;
if (top->next == NULL)
{
printf("Empty Stack\n");
return;
}
else
{
FirstCell = top->next;
top->next = top->next->next;
free(FirstCell);
}
}
Element ReturnTopStack(Stack*top)//返回栈顶元素
{
if (top->next == NULL)
{
printf("Empty Stack\n");
return NULL;
}
else
{
printf("栈顶元素为:%d \n",top->next->val);
return top->next->val;
}
}
void StackElementPrint(Stack*top)
{
Stack* cur = top->next;
while (cur)
{
printf("%d ", cur->val);
cur = cur->next;
}
printf("\n");
}
水篇博客==如有疑惑或指正可发表
|