自2015年数据结构考研不可以用Java描述算法编程题,于是只能重新熟悉C,并学习C++,本质语法没有区别,但是链表各种指针不熟悉,出现写几行编译一下的情况,学习了一天大致自己能写出C++的单链表的添加删除和逆置,多链表就不成问题了
#include "bits/stdc++.h"
using namespace std;
const int N = 10;
typedef struct LNode
{
int data;
struct LNode *next;
}LNode;
void createList(LNode *head, int a[N])
{
LNode *p = head;
for (int i = 0; i < N; i++)
{
LNode *newnode = new LNode;
newnode->data = a[i];
p->next = newnode;
p = p->next;
}
}
void printList(LNode *head)
{
LNode *p = head->next;
while (p != NULL)
{
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
void reverseList(LNode *head)
{
LNode *p, *r;
p = head->next;
head->next = NULL;
while (p != NULL)
{
r = p->next;
p->next = head->next;
head->next = p;
p = r;
}
}
void deleteKNumber(LNode *head)
{
cout << "Which u want to delete" << endl;
int k;
cin >> k;
int count = 0;
LNode *p = head;
LNode *q = p;
while (p != NULL)
{
count++;
p = p->next;
if (count == k)
{
q->next = p->next;
delete p;
return;
}
q = q->next;
}
}
void destroy(LNode *head)
{
LNode *p = head, *r;
while (p != NULL)
{
r = p->next;
delete p;
p = r;
}
}
int main()
{
ios::sync_with_stdio(0);
int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
LNode *head = new LNode;
createList(head, a);
printList(head);
deleteKNumber(head);
printList(head);
puts("reverse:");
reverseList(head);
printList(head);
destroy(head);
printList(head);
return 0;
}
这几天复习掉数据结构,我看它还是主要注重时间复杂度的,题目难度都不难,都是数据结构本身的题目,没有实际情况遮遮掩掩(为了照顾跨考生?我听闻还有相当一部分的学生是直接背代码的…)
争取408数据结构能拿满分。