【问题标题】:Bubble sort of a double linked list doesn't stop running双链表的冒泡排序不会停止运行
【发布时间】:2012-01-05 20:44:04
【问题描述】:

方法如下

public void sortStudentsAlphabeticallyByFirstName()
{
    StudentNode unsorted = tail;
    StudentNode current = header;
    while(current != null)
    {
        while(current != unsorted)
        {
            int result = (current.nextNode().getFirstName()).compareToIgnoreCase(current.getFirstName());
            if(result < 0)
            {
                StudentNode temp = current;
                current = current.nextNode();
                current.setNext(temp);
            }
        }
        current = current.nextNode();
        unsorted = unsorted.prevNode();
    }
}

问题是执行时它一直在运行,并没有停止,我不确定问题出在哪里。

【问题讨论】:

  • 好吧,考虑一下你的内部 while 循环,看看是否存在它可能永远不会返回 false 的情况。这很明显 - 你应该看到它。但总的来说,在这样的问题中,调试输出是你最好的朋友。您应该在内部 while 循环中打印当前元素,您很快就会知道出了什么问题。既然这看起来像家庭作业,那我就不说了。
  • 您能否完成代码以便我们查看您使用的数据类型?
  • 你用的是什么输入法?请注意,如果 result 始终 >= 0,则 current 将永远不会前进。
  • @Dave Shaw :我已经为您制作了整个程序,请看一下。问候
  • @Dave Shaw :在这里观看这个新代码。问候

标签: java algorithm sorting


【解决方案1】:

假设我们的链接列表有 A、C、B 和 D 节点。当你进入第二个 while 循环时说

current = C;

所以使用这个代码:

temp = current; // i.e. temp = C as current = C
current = current.next(); // say current = B now and temp = C
current.setNext(temp); // here B's next is set to C
                       // but you forgot A's next is C in the example, now since B 
                       // is taking it's place so A's next must point to B
                       // B's next must point to C and C's next must point to D.

看来你忘记了这些步骤,

之后,当您将 current 移动到下一个节点时,temp 和 current 将交换。但是 temp 之前的那个,即示例中的 A 必须指向 B,它正在与 C 交换。由于 B 之前指向 D,现在交换后 C 必须指向 D(您错过了这部分)并且 B 必须指向C(这就是你在第三行所做的。)

编辑 已添加完整的工作代码以获取更多信息。

import java.io.*;

class Node
{
public Node previous;
public String value;
public Node next;
}

public class LinkedList
{
private BufferedReader br ;
private String str; 
private int totalNodes;

private  Node current, previous, temp, head, tail; 

public LinkedList()
{
    br = new BufferedReader(new InputStreamReader(System.in));
    current = previous = temp = head = tail = null;
    totalNodes = 0;
}

public static void main(String[] args)
{
    LinkedList ll = new LinkedList();
    ll.menu();
}

private void menu()
{
    boolean flag = true;
    int choice = 0;
    while(flag)
    {
        System.out.println("--------------------------------------------------");
        System.out.println("---------------------MENU-----------------------");
        System.out.println("Press 1 : To ADD Node at the END.");
        System.out.println("Press 2 : To ADD Node at the BEGINNING.");
        System.out.println("Press 3 : To Add Node in BETWEEN    the List.");
        System.out.println("Press 4 : To  SORT the List");
        System.out.println("Press 5 : To DISPLAY the List.");
        System.out.println("Press 6 : To EXIT the Program.");
        System.out.println("--------------------------------------------------");
        System.out.print("Please Enter your choice here : ");
        try
        {
            str = br.readLine();
            choice = Integer.parseInt(str);
            if (choice == 6)
            {
                flag = false;
            }
            accept(choice);
        }
        catch(NumberFormatException nfe)
        {
            System.out.println("OUCH!, Number Format Exception, entotalNodesered.");
            nfe.printStackTrace();
        }
        catch(IOException ioe)
        {
            System.out.println("OUCH!, IOException, entotalNodesered.");
            ioe.printStackTrace();

        }
    }
}

private void accept(int choice)
{
    switch(choice)
    {
        case 1:
            addNodeToListAtStart();
            break;
        case 4:
            sortListBubble();
            break;
        case 5: 
            displayList();
            break;
        case 6:
            System.out.println("Program is Exiting.");
            break;
        default:
            System.out.println("Invalid Choice.\nPlease Refer Menu for further Assistance.");
    }
}   

private void addNodeToListAtStart()
{
    if (head != null)
    {
        current = new Node();
        System.out.print("Enter value for the New Node : ");
        try
        {
            str = br.readLine();
        }
        catch(NumberFormatException nfe)
        {
            System.out.println("OUCH!, Number Format Exception, entotalNodesered.");
            nfe.printStackTrace();
        }
        catch(IOException ioe)
        {
            System.out.println("OUCH!, IOException, entotalNodesered.");
            ioe.printStackTrace();              
        }
        current.previous = tail;
        current.value = str;
        current.next = null;
        tail.next = current;
        tail = current;
    }
    else if (head == null)
    {
        current = new Node();
        System.out.print("Enter value for the New Node : ");
        try
        {
            str = br.readLine();
        }
        catch(NumberFormatException nfe)
        {
            System.out.println("OUCH!, Number Format Exception, entotalNodesered.");
            nfe.printStackTrace();
        }
        catch(IOException ioe)
        {
            System.out.println("OUCH!, IOException, entotalNodesered.");
            ioe.printStackTrace();              
        }
        current.previous = null;
        current.value = str;
        current.next = null;            
        head = current;
        tail = current;
    }
    totalNodes++;
}

private void displayList()
{
    current = head;
    System.out.println("----------DISPLAYING THE CONTENTS OF THE LINKED LIST---------");
    while (current != null)
    {
        System.out.println("******************************************");
        System.out.println("Node ADDRESS is : " + current);
        System.out.println("PREVIOUS Node is at : " + current.previous);
        System.out.println("VALUE in the Node is : " + current.value);
        System.out.println("NEXT Node is at : " + current.next);
        System.out.println("******************************************");
        current = current.next;
    }
}

private boolean sortListBubble()
{
    // For Example Say our List is 5, 3, 1, 2, 4
    Node node1 = null, node2 = null; // These will act as reference. for the loop to continue
    temp = head;    // temp is set to the first node.   

    if (temp == tail || temp == null)
        return false;

    current = temp.next; // current has been set to second node.

    for (int i = 0; i < totalNodes; i++) // this loop will  run till whole list is not sorted.
    {
        temp = head; // temp will point to the first element of the list.
        while (temp != tail) // till temp won't reach the second last, as it reaches the last element loop will stop.
        {
            if (temp != null)
                current = temp.next;
            while (current != null) // till current is not null.
            {
                int result = (temp.value).compareToIgnoreCase(current.value); 
                if (result > 0) // if elment on right side is higher in value then swap.
                {
                    if (temp != head && current != tail) // if nodes are between the list.
                    {
                        current.previous = temp.previous;
                        (temp.previous).next = current;
                        temp.next = current.next;
                        (current.next).previous = temp;                     
                        current.next = temp;
                        temp.previous = current;
                    }
                    else if (current == tail) // if nodes to be swapped are second last and last(current)
                    {
                        temp.next = current.next;
                        current.previous = temp.previous;
                        if (temp.previous != null)
                            (temp.previous).next = current;
                        else
                            head = current;
                        temp.previous = current;
                        current.next = temp;
                        tail = temp;
                    }
                    else if (temp == head) // if the first two nodes are being swapped.
                    {
                        temp.next = current.next;                       
                        (current.next).previous = temp;
                        current.previous = temp.previous;
                        temp.previous = current;
                        current.next = temp;
                        head = current;
                    }   
                    current = temp.next; // since swapping took place, current went to the left of temp, that's why
                                                   // again to bring it on the right side of temp.
                }
                else if (result <= 0) // if no swapping is to take place, then this thing
                {
                    temp = current;  // temp will move one place forward
                    current = current.next; // current will move one place forward
                }                                       
            }
            if (temp != null)
                temp = temp.next;
            else // if temp reaches the tail, so it will be null, hence changing it manually to tail to break the loop.
                temp = tail;
        }
    }
    return true;
}
}

希望这可能会有所帮助。

问候

【讨论】:

  • 好吧,我把它改成StudentNode temp = current; StudentNode next = current.nextNode(); StudentNode previous = current.prevNode(); StudentNode nextNext = next.nextNode(); current = current.nextNode(); current.setNext(temp); temp.setNext(nextNext); nextNext.setPrev(temp); previous.setNext(current); temp.setPrev(current); current.setPrev(previous);
  • @DaveShaw:我告诉你你做错了什么,我正在编辑我的答案。问候
【解决方案2】:

很久没看冒泡排序算法了,但是下面的部分好像不对

StudentNode temp = current;
current = current.nextNode();
current.setNext(temp);

假设您从节点 A -> B -> C(其中 A = 当前)开始。您将以 current = B(第 2 行)、current.next = A 结尾,但 current.next.next 又是最新的,因为您从未替换过 temp 变量的 next

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-04
    • 2022-01-09
    • 1970-01-01
    • 2011-04-13
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    相关资源
    最近更新 更多