如何解决如何重新排列 LinkedList 中的元素,以便负数先出现?它成功地结束了循环?
我是初学者,以下是我目前能想到的最好的。方法 .Split() 的目标是我应该重新排列(仅重新排列,不添加或删除节点,也不切换节点的数据)的元素LinkedIntList
例如,如果链表是 [1,5,-9,7,-5,78],结果应该是 [-9,1,78]。负值的顺序无关紧要。
只有一个私有字段,即ListNode前端;
我正在尝试使用 current.data < 0
来挑选负值并将它们放在列表的前面,从前面迭代,然后重新开始。确保它从列表中选择所有负值。但是我的输出一直陷入无限循环,无法中断。我不知道在这里做什么。
这是我对这个问题的最佳尝试。
public void Split()
{
ListNode current = front;
ListNode head = front;
while (current.next != null)
{
if (current.data < 0)
{
current.next = front; // set the pointer of current's node
front = current; // update the head with a negative value
current = current.next; // iterate from the front
}
else if (current.data >= 0)
{
current = current.next; // if positive,skip the process and keep iterating
}
else
{
break; // break if null or anything else
}
if (current.next == null || current == null)
{
break; // another attempt to break since it keeps getting stuck
}
}
}
解决方法
你好 llda:为了将负数向前移动,我建议通过两个相邻的指针来完成它。请参阅随附的演示想法图片。
代码如下:
public void Split(){
ListNode current = front.next;
ListNode prior = front;
ListNode head = front;
do {
if(current.data < 0 && current.next != null){
prior.next = current.next;
head = current;
head.next = front;
current = prior.next;
}
current = current.next;
prior = prior.next;
} while(current.next != null)
}
,
您必须更新所有相关引用以保持链表完整。
作为自制实现,我建议以这种方式进行完整排序(一种冒泡排序):
Customer
但更现代的 Java 风格是实现 ...
public void sort() {
ListNode item = front;
while (item.next != null) {
if (needSwapping(item,item.next)) {
item = swapItems(item,item.next);
if (item.prev != null) {
// one step back to check next against prev in next loop
item = item.prev;
}
} else {
item = item.next;
}
}
front = firstNode(item);
}
private ListNode swapItems(ListNode item,ListNode next) {
ListNode outerPrev = item.prev;
ListNode outerNext = next.next;
// change the refs of outer elements
if (outerPrev != null) {
outerPrev.next = next;
}
if (outerNext != null) {
outerNext.prev = item;
}
// change refs to outer elements
item.next = next.next;
next.prev = item.prev;
// change inner refs
item.prev = next;
next.next = item;
return next;
}
private boolean needSwapping(ListNode item,ListNode next) {
return item.data > next.data;
// here is the point for optimizations of sort accuracy eg. negatives order doesn't matter
// return item.data >0 && item.data > next.data;
}
...
接口或提供 Comparable
并使用 here 或 stackoverflow 中描述的 Comparator
方法{3}}。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。