2011-03-08 198 views
0

这是我的链接列表实现。该程序正常工作。你会在功能/性能/内存使用方面有任何意见吗?使用链接列表实现堆栈实现

#include <stdafx.h> 
#include <stdlib.h> 
#include <stdio.h> 

struct node 
{ 
int data; 
struct node * next; 
}; 

int length(struct node * current) 
{ 
int len = 0; 
while(current) 
{ 
len++; 
current = current->next; 
} 
return len; 
} 

struct node* push(struct node* stack, int data) 
{ 
    struct node * current = stack; 
    struct node * newNode = (node*)(malloc(sizeof(node*))); 
    newNode->data = data; 
    newNode->next = NULL; 
    //length(current); 
    //single element case 
    if(stack == NULL) 
    {   
    stack = newNode; 
    } 
    else// multiple element case 
    { 
     while(current!=NULL) 
     { 
      if(current->next==NULL){ 
       current->next = newNode; 
       break; 
       } 
      else 
      { 
      current = current->next; 
      } 
     } 
    } 

    return stack; 
} 

bool isemp(struct node * stack) 
{ 
    if(stack == NULL) 
    { 
    printf("Stack is empty"); 
    return true; 
    } 
    else{ 
     return false; 
    } 
} 

struct node * pop(struct node * stack) 
{ 

struct node * current = stack; 
struct node * previous = NULL; 
bool isempty = false; 
while(!isemp(stack)&& current) 
    { 
     if(current->next==NULL) 
     { 
     //delete previous; 

      if(previous) 
      { 
      previous->next = NULL; 
      printf("Popped element is %d ", current->data); 
      current = current->next; 
      } 
      else if(length(stack)==1) 
      { 
      printf("Pop last element %d",stack->data); 
      stack = NULL; 
      current = NULL; 
      } 
     } 

     else 
     { 
     previous = current; 
     current = current->next; 
     //stack = current; 
     } 
    } 
    return stack; 
} 


void main() 
{ 
    struct node * stack = NULL; 
    int data = 1; 
    int index = 5; 
    while(index) 
    {  
     stack = push(stack,data); 
     data++; 
     index--; 
    } 
    while(stack!=NULL) 
    { 
    stack = pop(stack); 
    } 

} 
+1

无法读取...修复您的代码格式。 – andersoj 2011-03-08 03:42:40

+3

这个问题是不是更适合http://codereview.stackexchange.com/? – Pablo 2011-03-08 03:44:15

+1

目前还没有'codereview属于'... – 2011-03-08 03:47:11

回答

3

有在你的代码。在push()方法的问题,无数的号码,你这样做是:

 while(current!=NULL) 

    { 
     if(current->next==NULL){ 
      current->next = newNode; //This is also Wrong .You are not making Head pointing to newly created node 
      break; 
      } 
     else 
     { 
     current = current->next; //This is Wrong For Stack Implementation 
     } 
    }` 

什么你实际上做的是插入一个新创建的节点到最后的链表。因此有些队列通过链表实现。

+0

em ..在推我添加新的节点在尾巴,所以当我弹出我从尾巴删除节点以及。我的想法是堆栈操作的主要目的是从同一端添加和删除节点。你将如何编码堆栈实现,你是否喜欢插入和从头部删除节点? – user457660 2011-03-08 06:45:56

+1

@ user457660是的,我确实希望在开始时插入节点,因为这只是计算上的O(1).Also pop()也是O(1)。如果它有帮助,请接受这个答案。 – Algorithmist 2011-03-08 14:04:32

0

实现相同在一个新的项目被添加到列表的起始端,并从同一端.The边界条件处理不当POP操作的链接
http://codepad.org/dRMwSOuO
做的一种方式though.Still时间复杂度会更好,因为您不必在列表中遍历直到结束。