【问题标题】:delete alternate nodes in linked list in java在java中删除链表中的备用节点
【发布时间】:2017-07-09 20:36:08
【问题描述】:
我正在编写删除链表中备用节点的代码。为什么它进入无限循环?
输入: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;
}
块引用
【问题讨论】:
标签:
java
singly-linked-list
【解决方案1】:
由于有几点,一些提示:
- 保持代码/逻辑简单。如果不需要,则没有带有两个变量和两个条件的循环。在这里你是直线行走。
- 循环条件(
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.
}
【解决方案2】:
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(head);
I/P:5 10 15 25 35 25 40 O/P:5 15 35 40
【解决方案3】:
/**
*
* 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;
}