1、合并有序链表
#include<iostream>
using namespace std;
struct ListNode
{
int val;
ListNode* next;
ListNode():val(0),next(nullptr){}
ListNode(int x) :val(x), next(nullptr) {}
};
ListNode* createlist(int n) //创建长度为n的链表
{
ListNode* head = new ListNode(); //创建空的头节点,此后一直认为头节点是空的
ListNode* p = head; //创建指针指向头节点
for (int i = 0; i < n; i++)//用for循环输入节点的数,建立链表
{
int x = 0;
cin >> x;
ListNode* newnode = new ListNode(x);
head->next = newnode;
head = head->next;
}
head = p; // 输入到此结束
return head;
}
ListNode* merge_recursion(ListNode* h1, ListNode* h2)
{
if (!h2)
return h1;
if (!h1)
return h2;
if (h1->val < h2->val)
{
h1->next = merge_recursion(h1->next, h2);
return h1;
}
else
{
h2->next = merge_recursion(h1, h2->next);
return h2;
}
}
void print(ListNode* h) //打印链表,参数为某链表的头指针,操作不改变实参
{
ListNode* n = h->next; // 因为带头节点,因此需要从head->next开始遍历链表
if (n == nullptr) //若是空链表,输出 NULL
cout << "NULL" << endl;
else
{
while (n != nullptr)
{
cout << n->val << ' ';
n = n->next;
}
cout << endl;
}
}
int main()
{
int n1 = 0;
int n2 = 0;
while (cin>>n1)
{
cin >> n2;
ListNode* h1 = createlist(n1);
ListNode* h2 = createlist(n2);
ListNode* h = new ListNode();
h->next = merge_recursion(h1->next, h2->next);
print(h);
}
return 0;
}
2、栈:括号
#include<iostream>
#include<string>
using namespace std;
bool istrue(string s)
{
string stack[20];
int top = 0;
for (int i = 0; i < s.length(); i++)
{
if (s[i] == '(')
{
stack[top++] = '(';
}
else
{
if (top == 0)
return false;
top--;
}
}
if (top == 0)
return true;
else
return false;
}
int main()
{
int n = 0;
cin >> n;
while (n--)
{
string s;
cin >> s;
if (istrue(s))
cout<< "TRUE"<<endl;
else
cout<<"FALSE"<<endl;
}
}
3、maxtoend
#include<iostream>
using namespace std;
struct List
{
int data;
List* next;
};
void append(List* p, int x)
{
List* q = p;
p = p->next;
while (p != NULL)
{
q = p;
p = p->next;
}
List* t = new List();
t->data = x;
q->next = t;
t->next = p;
}
void maxtoend(List* p)
{
List* q = p;
List* pmax = q;
List* pre = q;
p = p->next;
while (p != NULL)
{
if ((pmax->data) < (p->data))
{
pre = q;
pmax = p;
}
q = p;
p = p->next;
}
List* t = new List();
t->data = pmax->data;
q->next = t;
t->next = p;
pre->next = pmax->next;
}
int main()
{
int n;//有多少ge数据
List* head = new List();
head->next = NULL; // 创建带头节点的链表
while (cin >> n)
{
append(head, n);
}
maxtoend(head);
List* f = head->next; // 因为带头节点,因此需要从head->next开始遍历链表
if (f == NULL)
{
cout << "NULL";
}
while (f != NULL)
{
cout << f->data << " ";
f = f->next;
}
return 0;
}