关于链表的疑惑
以下是我写的代码,关于注释中的代码,大佬们有没有知道如何在控制台程序控制输出,就是会停顿一下。哦,关于sll_reverse()函数有没有更好的办法,我想不出来。
#include <stdlib.h>
#include <stdio.h>
#include "singly_linked_list.h"
//struct NODE * sll_reverse(struct NODE * first);
int sll_remove(Node ** rootp, int value);
int dll_insert(Node ** rootp, int value);
Node * sll_reverse(Node *first);
int main(){
int num;
Node *first = (Node *)malloc(sizeof(Node));
if(first == NULL){
perror("NO Buffle: ");
return 1;
}
first->value = 3;
first->link = NULL;
Node *rootp = first;
while (scanf("%d" , &num) != EOF){
dll_insert(&rootp, num);
}
Node * ptr = rootp;
printf("\n");
while(ptr != NULL){
printf(" %d", ptr->value);
ptr = ptr->link;
}
/* getchar();getchar();
printf("Input a single number you want to remove: ");
getchar();
while(scanf("%d", &num) != EOF){
sll_remove(&rootp, num);
}
ptr = rootp;
while(ptr != NULL){
printf(" %d", ptr->value);
ptr = ptr->link;
}*/
rootp = sll_reverse(rootp);
printf("\n");
ptr = rootp;
while(ptr != NULL){
printf(" %d", ptr->value);
ptr = ptr->link;
}
ptr = rootp;
while(ptr != NULL){
Node * temp=ptr;
ptr = ptr->link;
free(temp);
}
return 0;
}
int dll_insert(Node ** rootp, int value){
Node *previous = NULL;
Node *current = *rootp;
while(current != NULL && current->value < value){
previous = current;
current = current->link;
}
if (current != NULL && current-> value == value)
return 0;
Node *new = (Node *)malloc(sizeof(Node));
if (new == NULL){
perror("NO buffle : ");
exit(EXIT_FAILURE);
}
new->value = value;
new->link = current;
if(previous != NULL){
previous->link = new;
}
else{
*rootp = new;
}
return 0;
}
int sll_remove(Node ** rootp,int value){
Node *previous = NULL;
Node *current = *rootp;
while(current != NULL && current->value != value){
previous = current;
current = current->link;
}
if(current != NULL){
Node * temp = current;
current = current->link;
free(temp);
if(previous != NULL){
return 0;
}
else {
*rootp = current;
return 0;
}
}
else {
printf("No this module. ");
return 1;
}
}
Node * sll_reverse(Node * first){
int i = 0;
Node *temp = first;
while(temp != NULL){
temp = temp->link;
i++;
}
if( i == 0){
printf("None Node.");
return first;
}
Node *array[i];
temp = first;
for(int j = 0; j< i;j++){
array[j] = temp;
temp = temp->link;
}
Node *new = array[i-1];
for(int k = i-1;k >= 0;k--){
temp = array[k];
if(k != 0){
temp->link = array[k-1];
}
else{
temp->link = NULL;
}
}
return new;
}
头文件single_link_list.h
typedef struct NODE {
int value;
struct NODE * link;
}Node;