反向链表问题

时间:2011-04-01 07:30:17

标签: java linked-list reverse

我在java中有以下链表程序,除反向链表功能外,它工作正常。我错过了什么?

public class LinkedList {

private Link first;

public LinkedList()
{
    first = null;
}
public boolean isEmtpy()
{
    return(first==null);
}

public void insertFirst(int id, double dd)
{
    Link newLink=new Link(id,dd);
    newLink.next=first;     //new link --> old first
    first =newLink;         //first --> newLink
}
public Link deleteFirst()
{
    Link temp=first;
    first=first.next;
    return temp;
}
public void displayList()
{
    Link current=first;
    System.out.println("List (first-->last)");
    while(current!=null)
    {
        current.displayLink();
        current=current.next;
    }       
    System.out.println(" ");
}
public Link find(int key)
{
    Link current=first;

    while(current.iData!=key)
    {
        if(current.next==null)
            return null;    //last link
        else
            current=current.next;

    }
    return current;
}
public Link delete(int key)
{
    Link current=first;
    Link previous=first;

    while (current.iData!=key)
    {
        if (current.next==null)
            return null;
        else
        {
            previous=current;
            current=current.next;
        }
    }
    if(current==first)
        first=first.next;
    else
        previous.next=current.next;
    return current;     
}   

public void insertAfter(int key, int id, double dd)
{
    Link current=first;
    Link previous=first;

    Link newLink = new Link(id,dd);
    while (current.iData!=key)
    {
        if (current.next==null)
            System.out.println("At the last Node");
        else
        {
            previous=current;
            current=current.next;

        }
    }
    System.out.println("Value of previous "+ previous.iData);
    System.out.println("Value of current after which value will be inserted is " + current.iData);
    newLink.next=current.next;
    current.next=newLink;
}

public Link reverse()
{
    Link previous=null;
    Link current=first;
    Link forward;

    while(current!=null)
    {
        forward=current.next;
        current.next=previous;
        previous=current;
        current=forward;
    }
    return previous;
}
}

3 个答案:

答案 0 :(得分:7)

问题是,reverse()未将first设置为新值,因此链接列表将被破坏(实际上它将缩减为前一个元素)。

你应该添加

first = previous;

最后,在返回值之前(或者 - 你真的需要返回新的头节点吗?)。

答案 1 :(得分:0)

这是更改的代码。你需要将last的next设置为null并首先重新初始化。

public Link reverse()
{
    Link previous=null;
    Link current=first;
    Link forward;

    while(current!=null)
    {
        forward=current.next;
        current.next=previous;
        previous=current;
        current=forward;
    }
    first.next = null;
    first = previous;
    return previous;
}
}

答案 2 :(得分:-1)

新头回来了,对吗?我认为初始头的下一个应设置为null,否则它将在遍历列表时在最后两个元素之间循环。

嘿,别介意......