【发布时间】:2018-09-03 00:07:05
【问题描述】:
我对这个编程世界和 Java 完全陌生,我在尝试链接列表时遇到了一个问题,同时尝试对 0、1 和 2 的链接列表进行排序。谁能说明我做错了什么?我在这里附上了我的代码。这件事基于我的逻辑,它应该可以正常工作,但不幸的是它实际上是在返回列表而不进行排序。
对0、1、2的链表排序
class LinkedList
{
Node head;
class Node
{
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
Node sortList(Node h)
{
if(h!=null || h.next!=null)
{
return h;
}
Node zero = new Node(0);
Node one = new Node(0);
Node two = new Node(0);
Node curr = h;
while(curr!=null)
{
if(curr.data == 0)
{
zero.next = curr;
zero = zero.next;
curr = curr.next;
}
else if(curr.data == 1)
{
one.next = curr;
one = one.next;
curr = curr.next;
}
else
{
two.next = curr;
two = two.next;
curr = curr.next;
}
}
zero.next = (one.next !=null) ? (one.next): (two.next);
one.next = two.next;
two.next = null;
h = zero.next;
return h;
}
/* Inserts a new Node at front of the list. */
public void push(int new_data)
{
Node new_node = new Node(new_data);
new_node.next = head;
head = new_node;
}
void printList(Node h)
{
Node temp = h;
while (temp != null)
{
System.out.print(temp.data+" ");
temp = temp.next;
}
System.out.println();
}
public static void main(String args[])
{
LinkedList llist = new LinkedList();
llist.push(0);
llist.push(1);
llist.push(0);
llist.push(2);
llist.push(1);
llist.push(1);
llist.push(2);
llist.push(1);
llist.push(2);
System.out.println("Linked List before sorting");
llist.printList(llist.head);
Node h=llist.sortList(llist.head);
System.out.println("Linked List after sorting");
llist.printList(h);
}
}
【问题讨论】:
-
首先排序函数立即退出而不进行排序,因为
if(h!=null || h.next!=null)
标签: java data-structures singly-linked-list