我正在编写用于删除链表中备用节点的代码。为什么它进入无限循环? 输入: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 = p ;
p.next = q;
System.out.println(p.data+" "+q.data);
}
return head;
}
块引用
答案 0 :(得分:0)
由于有几点,一些提示:
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.
}
答案 1 :(得分:0)
public void DeleteAlternateNodes(Node head) {
Node current=head;
Node prev=head;
if(head==null)
return;
else if(current.next==null)
return;
while(current!=null && current.next!=null)
{
prev.next=current.next.next;
current=current.next;
prev=prev.next;
}
}
DeleteAlternateNodes(头);
I / P:5 10 15 25 35 25 40 O / P:5 15 35 40
答案 2 :(得分:0)
/**
*
* 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;
}