在java中删除链表中的备用节点
我正在编写代码来删除链表中的备用节点。为什么它是无限循环的? 输入:5->11->13->12->15->5 预期操作:5->13->15->5在java中删除链表中的备用节点,java,singly-linked-list,Java,Singly Linked List,我正在编写代码来删除链表中的备用节点。为什么它是无限循环的? 输入:5->11->13->12->15->5 预期操作:5->13->15->5 public Node deleteAlternate(Node head) { Node p = head; Node q = head.next; while(q!=null && q.next !=null) { p.next = q.next; q.next =
public Node deleteAlternate(Node head)
{
Node p = head;
Node q = head.next;
while(q!=null && q.next !=null)
{
p.next = q.next;
q.next = p ;
p.next = q;
System.out.println(p.data+" "+q.data);
}
return head;
}
大宗报价
由于有几点,有一些提示: 保持代码/逻辑简单。如果不需要,则没有包含两个变量和两个条件的循环。这里你是直线行走。 必须改变q上的循环条件,因此q必须走。 调试,或者最好先在纸上完成。 比如:
public Node deleteAlternate(Node head)
{
Node p = head;
while (p != null) {
if (p.next != null) {
p.next = ... // delete the next.
}
p = p.next;
}
return head; // head is never deleted.
}
白头翁
I/p:5 10 15 25 25 40 O/p:5 15 35 40您应该进行一些调试。欢迎使用堆栈溢出!看起来您需要学习使用调试器。请随便吃点。如果您事后仍有问题,请随时回来,并提供一份证明您的问题的报告。
/**
*
* Input : 1 -> 2 -> 3 -> 4 -> 5
* Output : 1 -> 3 -> 5
*
* Input : 1
* Output : 1
*
* Input : 1 -> 2
* Output : 1
*
* Input : null
* Output : null
*
*/
public Node deleteAlternateNodes(Node<T> head) {
Node<T> newHead = head;
Node nextNode = null;
while(head != null && head.next != null) {
nextNode = head.next;
head.next = nextNode.next;
head = head.next;
}
return newHead;
}
/**
*
* Input : 1 -> 2 -> 3 -> 4 -> 5
* Output : 1 -> 3 -> 5
*
* Input : 1
* Output : 1
*
* Input : 1 -> 2
* Output : 1
*
* Input : null
* Output : null
*
*/
public Node deleteAlternateNodes(Node<T> head) {
Node<T> newHead = head;
Node nextNode = null;
while(head != null && head.next != null) {
nextNode = head.next;
head.next = nextNode.next;
head = head.next;
}
return newHead;
}