0
此场景应采用何种逻辑。删除链接列表中的偶数节点并以反向打印
我有一个线性链表。我想从倒数第二个节点开始以相反的顺序打印列表,但同时删除偶数个节点。 (节点1-奇数),65(节点2-偶数),733(节点3-奇数),34(节点4-偶数), 56(节点5-奇数),33(节点6 - 甚至)..
现在,我想要这样的输出.. 56(第二个最后节点),733(节点4被删除是偶数,它被打印为奇数),34(再次被删除,奇数印在相反的形式)..等等。
请告诉我,如果我没有清除我的问题。并帮助我理解逻辑。 感谢
更新
// Task A
public class LinkedList {
protected class NodeReference {
int info;
NodeReference next;
public NodeReference pLoc;
}
NodeReference headRef,pLoc, Loc;
int totalElements;
private NodeReference next;
public LinkedList() {
totalElements = 0;
headRef = null;
}
public void insertAtFront(int value) {
NodeReference newNode = new NodeReference();
newNode.info = value;
newNode.next = headRef;
headRef = newNode;
}
// Task B
public void printList(){
NodeReference location = headRef;
if(headRef!=null) {
System.out.println("The list is being printed....");
while(location != null) {
System.out.println(location.info);
location = location.next;
}
} // if block ends
else
System.out.println("Sorry, List is Empty!");
}
// Task C
public NodeReference reverseList(NodeReference headRef) {
if(headRef==null || headRef.next == null)
return headRef;
NodeReference pLoc1 = headRef;
NodeReference pLoc2 = headRef.next;
headRef.next = null;
while(pLoc1!= null || pLoc2!= null){
NodeReference tempRef = pLoc2.next;
pLoc2.next = pLoc1;
pLoc1 = pLoc2;
if (tempRef != null){
pLoc2 = tempRef;
}else{
break;
}
}
return pLoc2;
}
public void reverse() {
reverseList(headRef);
}
// Task D
public void deleteEven() {
Loc = headRef; pLoc = null;
while (Loc != null) {
Loc = (Loc.next).next;
System.out.println(Loc.info);
}
}
}
驱动程序
public class LinkedListDriver {
public static void main(String[] args) {
// TODO Auto-generated method stub
LinkedList l = new LinkedList();
l.insertAtFront(4); l.insertAtFront(7);
l.insertAtFront(3); l.insertAtFront(2);
l.insertAtFront(8); l.insertAtFront(4);
l.insertAtFront(6);
l.printList();
System.out.println("Printing Just Odd Values While Deleting Evens");
try {
l.deleteEven();
} catch(Exception e) {
System.out.println(" End of the List..");
}
}
}
您可以使用LinkedList#descendingIterator,然后使用此迭代器在列表上迭代并每隔两个元素跳过一个元素。请参阅https://docs.oracle.com/javase/8/docs/api/java/util/LinkedList.html#descendingIterator-- –
我知道这一点..但我没有陷入执行它完全进入程序.. –
它不会为我提供一些即时复制粘贴代码负责。请显示你的尝试。 –