今天面试给“宇龙酷派”鄙视了。我想说,其实链表反转我会!
单链表:初始化、创建、显示、删除、插入特定位置、删除特定位置、反转操作。
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#include <string.h>
typedef struct student
{
int data;
struct student* next;
}Node;
//初始化
Node* InitNode()
{
Node* head;
head = (Node*)malloc(sizeof(Node));
if (NULL == head)
{
printf("Failed to initialize.\n");
return NULL;
}
head->next = NULL;
}
//输入数据
Node* CreatNode(Node* head)
{
if (NULL == head)
{
printf("The head is NULL.\n");
return NULL;
}
Node* pre = head;
printf("CreatNode: enter a data:\n");
int itmp;
while (scanf("%d", &itmp)) //ctrl+z 结束
{
Node* tmp;
tmp = (Node*)malloc(sizeof(Node));
if (NULL == tmp)
{
printf("Initialize new node fail.\n");
return head;
}
tmp->data = itmp;
tmp->next = NULL;
pre->next = tmp;
pre = tmp;
}
return head;
}
//显示
Node* PrintNode(Node* head)
{
if (NULL == head)
{
printf("The head is NULL.\n");
return NULL;
}
Node* pre = head->next;
printf("The list is:\n");
while (pre)
{
printf("%d ", pre->data);
pre = pre->next;
}
printf("\n");
return head;
}
//计算
int CalcNode(Node* head)
{
if (NULL == head)
{
printf("The head is NULL.\n");
return 0;
}
Node* pre = head->next;
int num = 0;
while (pre)
{
num++;
pre = pre->next;
}
return num;
}
//删除
void DelNode(Node* head)
{
if (NULL == head)
{
printf("The head is NULL.\n");
exit(1);
}
Node* delp = head->next;
while (delp)
{
Node* tmp = delp->next;
free(delp);
delp = tmp;
}
printf("The head is cleared.\n");
}
//删除指定某个
Node* DelposNode(Node* head, int pos) //pos = 0,1,2..
{
if (NULL == head)
{
printf("The head is NULL.\n");
return NULL;
}
if (pos > CalcNode(head))
{
printf("The position is illegal.\n");
return NULL;
}
Node* p1 = head;
Node* p2 = p1->next;
Node* p3 = p2->next;
int itmp = pos;
while (itmp != 0)
{
p1 = p1->next;
p2 = p1->next;
p3 = p2->next;
itmp--;
}
if (p2 != NULL)
{
free(p2);
p1->next = p3;
}
return head;
}
//反转:1、保存原先链表,并while遍历
// 2、取出head节点做新链表头
// 3、利用头插入法将取出的原先元素存入新表中
Node* ReverseNode(Node* head)
{
if (NULL == head)
{
printf("The head is NULL.\n");
return NULL;
}
Node* oldnow = head->next; //遍历原先链表 节点
head->next = NULL; //原先链表清空,取出head节点
while (oldnow)
{
Node* tmp = oldnow->next; //保存oldnow后一个节点
/*头插法插入新节点*/
Node* newtmp = head->next;
head->next = oldnow; //放入新链表head后面
head->next->next = newtmp; //确保链接还原
oldnow = tmp; //now跳入原先链表的下个节点
}
return head;
}
//插入
Node* InserNode(Node* head, int pos, int data) //pos = 1,2,..
{
if (NULL == head)
{
printf("The head is NULL.\n");
return NULL;
}
if (pos > CalcNode(head))
{
printf("The position is illegal.\n");
return NULL;
}
Node* pre = head;
Node* now = pre->next;
int num = pos;
while (pos--) //寻找到位置
{
pre = pre->next;
now = now->next;
}
if (now != NULL) //now为当前插入的位置
{
Node* newp = (Node*)malloc(sizeof(Node));
newp->data = data;
pre->next = newp; //重新拼接,把now接上新的节点newp后
pre->next->next = now;
}
return head;
}
int main(void)
{
Node* head = InitNode();
CreatNode(head);
PrintNode(head);
InserNode(head, 0, 100);
PrintNode(head);
//Delete
DelNode(head);
// PrintNode(head);
return 0;
}