在不改变链表的情况下从尾到头打印连表
输入一个连表的头结点,从尾到头反过来打印出每个结点的值。
C#语言实现:
publicstaticvoidPrintRev(LinkedList<int>lList){Stack<int>stack=newStack<int>();foreach(intiteminlList){stack.Push(item);}while(stack.Count>0){Console.WriteLine(stack.Pop());}}
Java语言实现:
privatestaticvoidprintRev(LinkedList<Integer>lLink){Stack<Integer>stack=newStack<Integer>();Iterator<Integer>it=lLink.iterator();while(it.hasNext()){stack.push(it.next());}while(!stack.isEmpty()){System.out.println(stack.pop());}}
Python语言实现:
classNode(object):"""单链表节点"""def__init__(self,data=None,next=None):self.data=dataself.next=nextclassLinkedList(object):def__init__(self,node=None):self.node=nodedefprint_link_rev(self):"""逆序打印链表:return:"""lst=[]node=self.nodewhilenode:lst.append(node.data)node=node.nextfordatainsorted(lst,reverse=True):print(data)
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。