基础操作需要创建链表来存储数据
使用尾插法和尾删法来表示栈中的入栈和出栈
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
typedef struct node { int data; struct node* next; }Node,*LPNode; LPNode creatnode( int data) { LPNode newnode = (LPNode) malloc ( sizeof (Node)); assert (newnode); newnode->data = data; newnode->next = NULL; return newnode; } void insertbytail(LPNode &head, int data) //这里要么传引用要么传二级指针因为这里head赋值并没有对主函数里面的head改变 { if (head == NULL) { head = creatnode(data); } else { LPNode newnode = creatnode(data); LPNode pmove = head; while (pmove->next!=NULL) { pmove = pmove->next; } pmove->next = newnode; } } void deletetail(LPNode head) { LPNode pronode = head; if (head == NULL) { return ; } LPNode posnode = head->next; if (pronode->next == NULL) { cout << pronode->data; free (pronode); return ; } while (posnode->next!= NULL) { pronode = posnode; posnode = posnode->next; } cout << posnode->data ; free (posnode); pronode->next = NULL; } |
创建栈结构
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
typedef struct stack { int top; //用来判断是否为空 LPNode head; }Stack,*LPStack; //描述一个栈的最初始的状态 LPStack creatstack() { LPStack stack = (LPStack) malloc ( sizeof (Stack)); assert (stack); stack->top = 0; stack->head = NULL; return stack; } |
出栈入栈就是表现为链式结构的表尾插入和删除
1
2
3
4
5
6
7
8
9
10
|
void push(LPStack stack, int data) { insertbytail(stack->head, data); stack->top++; } void pop(LPStack stack) { deletetail(stack->head); stack->top--; } |
判断栈是否为空即判断 top==0
1
2
3
4
|
bool empty(LPStack stack) { return stack->top == 0; } |
代码实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
int main() { LPNode head = NULL; LPStack stack = creatstack(); int n; int num; cin >> num; //表示数 cin >> n; //表示进制 while (num) { push(stack,num%n ); num /= n; } while (!empty(stack)) { pop(stack); } return 0; } |
以上就是c/c++链式堆栈描述进制转换问题示例解析的详细内容,更多关于c/c++链式堆栈描述进制转换的资料请关注服务器之家其它相关文章!
原文链接:https://blog.csdn.net/weixin_56366633/article/details/121243865