tim
tim

Reputation: 1

how to understand the shallow copy

public class noorderedlist {
        node head;  
  public void afadd(int element){
        node newnode=new node(element);
        if(head==null){
            head=newnode;
            return; 
            }
            node temp=head;
    while(temp.next != null){
                temp = temp.next;
            }
            temp.next = newnode;
        }
  public void print(){
        node currentnode=head;
        while(currentnode!=null){
            System.out.print(currentnode.element);
            currentnode=currentnode.next;
        }
public class node {
    node next=null;
    int element;
    public node(int element){
        this.element=element;
    }

i want to write method to add point in a single link list,it works but i have a problem.why the head will change after the change of the temp?i hear about that is the shallow copy,but why the shallow copy does not work in"temp=temp.next"?,according to that in the loop the temp is changing then the head should change like "head=temp.next", but when i execute the print method the element of the head does not change but it adds a new point in the end of the link list. so what's going on here?

Upvotes: 0

Views: 34

Answers (0)

Related Questions