我制作了一个程序,用于存储学生和学生的课程 但是我想用最小到最大的ID形式对所有学生进行排序 现在我有它从大到小但我不知道如何改变它 我试着改变“>”到“<”但它不起作用。
这是我的插入方法
private Student addStudentRecord(Student head, Student tempADDACCOUNT) {
// IF there is no list, newNode will be the first node, so just return it
if (head == null) {
head = new Student(tempADDACCOUNT, head);
return head;
}
// ELSE, we have a list. Insert the new node at the correct location
else {
// We need to traverse to the correct insertion location...so we need a help ptr
Student helpPtr = head;
// Traverse to correct insertion point
while (helpPtr.getNext() != null) {
if (helpPtr.getNext().getID() > tempADDACCOUNT.getID())
break; // we found our spot and should break out of the while loop
helpPtr = helpPtr.getNext();
}
// Now make the new node. Set its next to point to the successor node.
// And then make the predecessor node point to the new node
Student newNode = new Student(tempADDACCOUNT, helpPtr.getNext());
helpPtr.setNext(newNode);
}
// Return head
return head;
}
如果你可以帮我把它从小到大排序 此方法是链接列表的插入方法。
答案 0 :(得分:0)
续......(在对问题的评论之后)
像
这样的东西 Student helpPtr = head;
Student prev = helpPtr;
while (helpPtr.getNext() != null) {
if (helpPtr.getNext().getID() < tempADDACCOUNT.getID())
break;
prev = helpPtr;
helpPtr = helpPtr.getNext();
}
Student newNode = new Student(tempADDACCOUNT, helpPtr);
prev.setNext(newNode);
注意:代码会给你一个想法,而不是经过测试。
答案 1 :(得分:0)
if (head == null) {
head = new Student(tempADDACCOUNT, head);
return head;
}
我喜欢这个
if (head == null||head.getID()> tempADDACCOUNT.getID()) {
head = new Student(tempADDACCOUNT, head);
return head;
}
所以问题就是如果我必须放的话 || head.getID()&GT; tempADDACCOUNT.getID()
现在每件事都在工作
答案 2 :(得分:0)
使用合并排序对链接列表进行排序,然后根据id
插入新节点这是我的合并排序示例代码`
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode sortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode fast = head;
ListNode slow = head;
ListNode prev = null;
// get center
while (fast != null && fast.next != null) {
prev = slow;
slow = slow.next;
fast = fast.next.next;
}
prev.next = null;
ListNode l1 = sortList(head);
ListNode l2 = sortList(slow);
return mregeList(l1, l2);
}
public ListNode mregeList(ListNode l1, ListNode l2) {
wif (l1 == null) {
return l2;
}
if (l2 == null) {
return l1;
}
ListNode result = null;
if (l1.val <= l2.val) {
result = l1;
result.next = mregeList(l1.next, l2);
} else {
result = l2;
result.next = mregeList(l1, l2.next);
}
return result;
}
}
您可以根据需要修改代码。 谢谢希望这会有所帮助。