链表应该是面试时被提及最频繁的数据结构!!!
下面是一个往链表末尾插入元素的操作:
typedef struct node{
int value;
node *next;
} node;
//往列表的末尾添加一个节点
node* insert_tail(node *head,int key){
node *new_node;
node *temp ;
temp = head;
new_node =(node *)malloc(sizeof(node));
new_node->value = key;
if(head == NULL){
head = new_node;
new_node ->next = NULL;
}else{
while(temp->next!=NULL){
temp = temp->next;
}
temp->next = new_node;
new_node->next = NULL;
}
return head;
}
题目:从尾到头打印链表
反向打印链表:
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
int value;
node *next;
} node;
typedef struct stack{
int key;
stack *pre;
stack *next;
} stack;
stack *head;
stack *bottom;
stack* push(int key){
if(head == NULL && head==bottom){
head = (stack*) malloc(sizeof(stack));
bottom = head;
bottom->key = key;
bottom->pre = bottom;
bottom->next= NULL;
}else{
//分配新的节点
stack *new_node;
new_node =(stack*) malloc(sizeof(stack));
new_node->key = key;
//连接到下一个节点
head->next = new_node;
new_node->pre = head;
//移动头指针到新的位置上
head = new_node;
head->next=NULL;
}
return head;
}
//反向打印链表的出栈操作
stack* pop_all_print(){
stack *temp;
//最后一个节点没有输出出来
if(head!=NULL && bottom!=NULL){
while(head!= bottom){
printf("node key: %d\n",head->key);
temp = head;
head = head->pre;
head->next = NULL;
free(temp);
}
//通过该方式将最后一个节点输出出来,并且释放内存
printf("node key: %d\n",head->key);
free(head);
head = bottom;
}
return NULL;
}
//反向打印链表
void reverse_print(node *link_head){
node *search;
search = link_head;
while(search !=NULL){
head = push(search->value);
search = search->next;
}
pop_all_print();
}
int main(){
node *link_head;
link_head = NULL;
for(int i=0;i<15;i++){
link_head = insert_tail(link_head,i);
}
reverse_print(link_head);
system("pause");
return 0;
}