# Java链表常见操作【剑指Offer】03:从尾到头打印链表

##### 题解一：递归
 1 /*
3  从最后一次到第一次，逆向的调用了后面的方法
4   */
5         static ArrayList<Integer> list = new ArrayList<>();
6         public static ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
7             if (listNode != null) {
10             }
11             return list;
12         }
##### 题解二：reverse()方法
1 public static ArrayList<Integer> printListFromTailToHead01(ListNode listNode) {
2         ArrayList<Integer> list = new ArrayList<Integer>();
3         while(listNode != null){
5             listNode = listNode.next;
6         }
7         Collections.reverse(list);//使用Collections的reverse方法，直接将list反转
8         return list;
9     }

public static class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}

1  public static void insetFromHead(ListNode head,ListNode newNode){
4         }

 1 public static void insertFromTail(ListNode head, ListNode newNode){
5                 return;
6             }
9             while (temp.next!=null){
10                 temp=temp.next;
11             }
12             temp.next=newNode;
13         }

1  public  static int length(ListNode head){
2             int len =0;
4             while(temp!=null){
5                 len++;
6                 temp=temp.next;
7             }
8             return len;
9         }

1  public static void printList(ListNode head){
3             while(temp != null){
4                 System.out.print(temp.val+" ");
5                 temp = temp.next;
6             }
7             System.out.println();
8         }

 1 public static boolean deleteFromIndex(ListNode head,int index){
3                 return false;
4             }
7                 return true;
8             }
10             //删除顺序为index的node只能将curNode停在index-1的位置
11             for(int curIndex =1;curIndex<index-1;curIndex++){
12                 curNode = curNode.next;
13             }
14             curNode.next=curNode.next.next;
15             return true;
16         }

 1 public static void main(String[] args) {
2         Scanner sc = new Scanner(System.in);
3         int nums = sc.nextInt();
4         ListNode headNode = new ListNode(1);
5         for(int i=2;i<=nums;i++){
7         }
10         System.out.println(list);
12         System.out.println(list1);
16         System.out.println(length);
17     }

1 2 3 4 5 6 7 8
[8, 7, 6, 5, 4, 3, 2, 1]
[8, 7, 6, 5, 4, 3, 2, 1]
1 2 4 5 6 7 8
7

posted @ 2020-02-20 16:08  reset_pc  阅读(...)  评论(...编辑  收藏