2011-04-07 57 views
0
#include <stdio.h> 
#include <stdlib.h> 
#include <conio.h> 

struct stackNode 
{ 
    int data; 
    struct stackNode *nextPtr; 
}; 


void instructions() 
{ 
    printf("[1]Push a value on the stack\n"); 
    printf("[2]Pop a value off the stack\n"); 
    printf("[3]Display the whole stack\n"); 
    printf("[4]Exit"); 
} 

void push(struct stackPtr *topPtr, int info) 
{ 
    struct stackPtr *newPtr; 
    newPtr= malloc(sizeof(struct stackNode)); 
    if(newPtr !=NULL) 
    { 
     newPtr->data = info; 
     newPtr->nextPtr=*topPtr; 
     *topPtr=newPtr; 
    } 
    else 
    { 
     printf("%d not inserted no memory available"); 
    } 

int main() 
{ 
    struct StackNodePtr *stackPtr; 
    stackPtr = NULL; 
    int choice, value; 
    do 
    { 
     instructions(); 
     printf("\nEnter Your Choice: "); 
     scanf("%d",&choice); 
     if(choice == 1) 
     { 
      printf("Enter a value for the stack");  
     }    
     if(choice == 2) 
     { 
      printf(" "); 
     }  
     if(choice == 3) 
     { 
      printf(" "); 
     } 
     if(choice == 4) 
     { 
      printf("bye!"); 
      return 0; 
     } 
    } while(choice !=4); 
    system("pause"); 
} 

我做了一個函數推送我的鏈表和堆棧代碼,但事情是它不工作有很大的錯誤,在功能推它有什麼問題嗎?它不允許使用malloc爲什麼?鏈接列表推送功能

+2

OMG,這就像是關於幾乎相同的事情的第六個問題......你真的在研究這個清單,不是嗎? – unwind 2011-04-07 10:09:00

+0

[typedef和鏈表]的可能重複(http://stackoverflow.com/questions/5552394/typedef-and-linked-list) – JeremyP 2011-04-07 11:06:37

回答

1
// just precede the struct type with ... struct 
struct stackNode* stackPtr = NULL; 

快樂編碼。

+0

這個怎麼樣?任何人都可以抄錄這個嗎? typedef struct stackNode StackNode; typedef struct StackNode * StackNodePtr; – 2011-04-07 10:08:00

+1

只要把它們拿出來?如果他們沒有被使用,他們沒有被使用。 – 2011-04-07 10:08:36

2

這是否適合您?

struct stackNode { int data; struct stackNode *nextPtr; }; 

int main() { struct stackNode * stackPtr = NULL; } 
+0

這是一樣的這個 ?? struct stackNode * stackPtr; stackPtr = NULL; ?? – 2011-04-07 12:05:44

+1

它是,但我更喜歡我的答案中的樣式,因爲我喜歡明確地初始化我的定義。 – 2011-04-07 12:28:28

2
struct stackNode 
{ 
    int data; 
    struct stackNode *nextPtr; 
}; 

int main() 
{ 
    struct stackNode *stackPtr = NULL; 
} 
+0

您正在創建一個全局變量。 – 2011-04-07 10:30:51

+0

@larsman:你是對的..固定 – Heisenbug 2011-04-07 10:39:09

1

這條線:

typedef struct StackNode *StackNodePtr; 

是錯誤的方式。你的類型定義應該是:

typedef struct stackNode StackNode; 
typedef StackNode* StackNodePtr; 

不知道爲什麼你反對使用typedef - 它往往使代碼更大量的可讀性。

+0

我只是想保持簡單,它讓我很困惑 ooppp不好意思,我該如何解決這個問題? typedef struct stackNode StackNode; typedef StackNode * StackNodePtr;沒有任何typdefs? – 2011-04-07 11:07:28

+0

@Kyel:我認爲@JohnKällén,@pst和@ 0verbose的其他答案已經向您展示瞭如何在不使用typedef的情況下編寫代碼 - 如果這不是您想要的,那麼您需要重新編寫問題。 – GrahamS 2011-04-07 11:31:34

+0

soo總結一下,只是這樣? – 2011-04-07 11:55:04