括号匹配,栈实现
#include <iostream>
#include <cstdlib>
#define MAXSIZE 100
using namespace std;
typedef struct
{
char a[MAXSIZE];
int top;
}stack;
void init(stack *s)
{
s->top =0;
}
void push(stack *s, char x)
{
s->a[s->top] = x;
s->top++;
}
void pop(stack *s)
{
s->top--;
}
int empty(stack s)
{
return(s.top?0:1);
}
char read(stack s)
{
returns.a[s.top-1];
}
int match_kuohao(char c[])
{
int i = 0;
stack s;
init(&s);
while(c[i]!='#')
{
switch(c[i])
{
case'(':
case'{':
case'[':
push(&s,c[i]);
break;
case'}':
if(!empty(s)&&read(s)=='{')
{
pop(&s);
break;
}
else
return 1;
case')':
if(!empty(s)&&read(s)==')')
{
pop(&s);
break;
}
else
return 1;
case']':
if(!empty(s)&&read(s)==']')
{
pop(&s);
break;
}
else
return 1;
}
i++;
}
return (empty(s));
}
int main()
{
char c[MAXSIZE] = {'(','3', '+', '5', ')', ']', '#'};
if(match_kuohao(c))
cout << "不匹配"<< endl;
else
cout << "匹配"<< endl;
return 0;
}
链表的创建,显示,合并,逆序,查找,插入,删除操作.
#include <iostream>
#include <cstdlib>
#include <stdio.h>
using namespace std;
typedef struct link_node
{
int info;
struct link_node *next;
}node;
node *init() //创建
{
node *p, *q,*head;
int x;
p = head = NULL;
while(scanf("%d",&x))
{
if(x == 0)break;
q =(node*)malloc(sizeof(node));
q->info = x;
if(head ==NULL)
head = q;
else
p->next =q;
p =q;
}
p->next =NULL;
return head;
}
void display(node *head) //显示
{
node *p;
p = head;
if(!p)
{
cout << "空"<< endl;
}
else
{
while(p)
{
printf("%d", p->info);
p =p->next;
}
printf("\n");
}
}
node *combine(node *head1, node *head2) //合并
{
node *p1;
p1 = head1;
while(p1)
{
if(p1->next == NULL) break;
p1 = p1->next;
}
p1->next= head2;
return head1;
}
node *transerve(node *head) //逆序
{
node *p1 = head;
node *p2 =p1->next;
node *p3 =p2->next;
p1->next= NULL;
while(p3)
{
p2->next = p1;
p1 =p2;
p2 =p3;
p3 =p3->next;
}
p2->next= p1;
return p2;
}
node *find(node *head, int i) //查找第i个节点的存放地址
{
int j = 1;
node *p = head;
while(p&& i!=j)
{
p = p->next;
j++;
}
return p;
}
node *insert(node *head, int i, int x) //第i个节点后插入值为x的新节点
{
node *q;
node *p = find(head,i);
if(!p&& i != 0)
cout << "找不到"<< endl;
else
{
q = (node*)malloc(sizeof(node));
q->info = x;
if(i == 0)
{
q->next = head;
head =q;
}
else
{
q->next = p->next;
p->next = q;
}
}
return head;
}
node *dele(node *head, int x)
{
node *pre = NULL,*p;
if(!head)
{
cout << "空"<< endl;
return head;
}
p = head;
while(p&& p->info!=x)
{
pre = p;
p = p->next;
}
if(!pre&& p->info ==x)
head = head->next;
else
pre->next =p->next;
free(p);
return head;
}
int main()
{
int x, i;
node *head1 = init(); //创建链表1
display(head1);
node *head2 = init(); //创建链表2
display(head2);
node *head3 =combine(head1,head2); //合并两个链表
display(head3);
node *head4 =transerve(head3); //逆序输出
display(head4);
scanf("%d%d",&i, &x);
node *head5 =insert(head4, i, x);
display(head5);
node *head6 =dele(head5, x);
display(head6);
return 0;
}