使用链表实现堆栈。 " ="之间的差异operator和setlink()函数

时间:2017-06-18 07:26:43

标签: linked-list stack

这是我的代码

import java.util.*;

class node{

public int data;
public node link;

public node()
{
    data = 0;
    link = null;
}

public node(int d, node l)
{
    data = d;
    link = l;
}

void setlink(node n)
{
    link = n;
}

void setdata(int dat)
{
    data = dat;
}

int showdata()
{
    return data;
}

node showlink()
{
    return link;
}
}

class stack{

node top;
int size;

stack()
{
    top = null;
    size = 0;
}

void push()
{
    node npt = new node();
    size++;
    System.out.println("Enter the value you want to enter :");
    Scanner sc = new Scanner(System.in);
    int val;
    val = sc.nextInt();
    npt.setdata(val);

    if( top == null )
    {
        top = npt;
    }
    else
    {
        npt.setlink(top);
        top = npt;
    }
}

void pop()
{
    node npt = top;
    top = npt.showlink();
    size--;
}

void showstack()
{
    node nptr = top;
    int i = 1;
    while( nptr != null )
    {
        System.out.println("Data at position "+ i + " is : " + nptr.showdata());
        i++;
        nptr = nptr.showlink();
    }
}
}

class stacked{

public static void main(String args[])
{
    stack obj = new stack();
    int temp = 0;
    while( temp != 1 )
    {
        System.out.println("-- Enter 1 to exit -- 2 to push -- 3 to pop -- 4 to show Stack --");
        Scanner sc = new Scanner(System.in);
        temp = sc.nextInt();
        if(temp == 1)
        {
            break;
        }
        switch(temp)
        {


            case 2: obj.push();
                    break;

            case 3: obj.pop();
                    break;

            case 4: obj.showstack();
                    break;

        }
        temp++;
    }
}
}

我的问题是void push()中的class stack函数," ="之间的区别是什么?运算符和setlink()函数。

我的意思是为什么我们不能写npt = top;而不是npt.setlink(top);

" ="做什么以及如何完成参考?

由于

0 个答案:

没有答案