单链表的翻转

    xiaoxiao2021-03-25  95

    一次解决,还是蛮顺利的。大致思路就是用三个指针模拟。这篇博客已经通过画图讲的很清楚了http://blog.csdn.net/feliciafay/article/details/6841115

    import java.util.Scanner; class ListNode{ int data; ListNode next; } public class 单链表翻转 { private ListNode head; public void init(){//初始化链表 Scanner cin=new Scanner(System.in); ListNode tail=new ListNode(); ListNode p=new ListNode(); while(cin.hasNextInt()){ p=new ListNode(); p.data=cin.nextInt(); p.next=null; if (head==null) head=p; else tail.next=p; tail=p; } } public void Print(){//打印链表 if (head==null) return; ListNode p=head; while(p!=null){ System.out.print(p.data+" "); p=p.next; } System.out.println(); } public void reverse(){//翻转链表 if (head==null) return; ListNode p=head; ListNode q=head.next; head.next=null; while(q!=null){ ListNode r=q.next; q.next=p; p=q; q=r; } head=p; } public static void main(String[] args) {//测试 单链表翻转 test=new 单链表翻转(); test.init(); test.Print(); test.reverse(); test.Print(); } }

    转载请注明原文地址: https://ju.6miu.com/read-23633.html

    最新回复(0)