forked from zfman/AlgorithmCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedUtils.java
More file actions
80 lines (73 loc) · 1.3 KB
/
Copy pathLinkedUtils.java
File metadata and controls
80 lines (73 loc) · 1.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package leetcode.common;
/**
* 链表工具类
* @author 刘壮飞
* https://github.com/zfman.
* https://blog.csdn.net/lzhuangfei.
*/
public class LinkedUtils {
/**
* 数组转化为链表
* @param array
* @return
*/
public static ListNode arrayToLinkedList(int[] array){
if(array==null) return null;
//head node
ListNode root=new ListNode(-1);
ListNode p=root;
int size=array.length;
int i=0;
while(i<size){
ListNode q=new ListNode(array[i++]);
q.next=null;
p.next=q;
p=q;
}
return root.next;
}
/**
* 打印链表
* @param root
*/
public static void print(ListNode root) {
if(root==null) System.out.println("root is null");
else{
while(root!=null){
System.out.print(root.val);
if(root.next!=null){
System.out.print("->");
}
root=root.next;
}
System.out.println();
}
}
/**
* 求链表长度
* @param root
* @return
*/
public static int length(ListNode root) {
if(root==null) return 0;
int n=0;
while(root!=null){
root=root.next;
n++;
}
return n;
}
/**
* 返回指向链表尾部的指针
* @param root
* @return
*/
public static ListNode moveToTail(ListNode root) {
if(root==null) return null;
ListNode tail=root;
while(tail.next!=null){
tail=tail.next;
}
return tail;
}
}