单向链表操作,某司笔试题答案:
project1为链表新建,增、删节点,逆转等常规操作;
project2为链表数字指定和插入+,-或空格;
project3为聚类。
#include <iostream>
#include <vector>
using namespace std;
/* Project 1
定义一个单向链表node, 每个节点值为int.
定义函数void create_linklist(…, int n)来生成链表,链表长度由参数n传入,生成的链表要作为参数返回,而不是当初函数返回值返回,链表节点值为1,2,3...n。
定义函数reverse_linklist(...), 对参数传入的链表进行逆转。
定义函数insert_node(node *pHead, int Index, int Value ), 在指定链表位置Index插入指定Value
定义函数delete_node(node *pHead, int Index),删除链表位置Index所在的节点
定义函数delete_linklist(), 删除整个链表
main()函数:
1.调用create_linklist()生成链表
2.调用insert_node()插入节点
3.调用delete_node()删除节点
4.调用reverse_linklist()逆转
5.打印链表所有值
6.结束程序工作
*/
struct node {
int v;
node* n;
};
/* 链表长度由参数n传入,生成的链表要作为参数返回,而不是当初函数返回值返回,
链表节点值为1,2,3...n
*/
void create_linklist(node **pHead, int n) {
node *pEnd = nullptr;
//循环创建链表
for (int i = 1; i <= n; i++) {
node *temp = (node*) malloc(sizeof(node)); //在堆区分配空间创建变量
temp->v = i; //赋值
temp->n = NULL;
if (NULL == *pHead) {
*pHead = temp;
pEnd = temp;
} else {
pEnd->n = temp;
pEnd = temp;
}
}
return;
}
//对参数传入的链表进行逆转
void reverse_linklist(node **pHead) {
if (NULL == *pHead) {
return;
}
node *pNode;
pNode = *pHead;
node *Prev = NULL;
node *pNext = NULL;
while (NULL != pNode) {
pNext = pNode->n;
if (NULL == pNext) {
*pHead = pNode;
}
pNode->n = Prev;
Prev = pNode;
pNode = pNext;
}<