
PS:头插法实现较简单,但生成内容为原内容的逆序;尾插法则为正序生成
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
|
class ListNode{ public int val; public ListNode next; ListNode (int val) { this.val = val; } }
public class ListTest { /** * 头插法 * @param nums * @return */ public static ListNode headInsert(int[] nums) { ListNode head = null; ListNode tail = null; int len = nums.length, i=0; while (i < len) { tail = new ListNode(nums[i++]); tail.next = head; head = tail; } return head; } /** * 尾插法 * @param nums * @return */ public static ListNode tailInsert(int[] nums) { ListNode head = null; ListNode tail = null; int len = nums.length, i = 0; while (i < len) { if (head == null) { head = tail = new ListNode(nums[i++]); }else { tail.next = new ListNode(nums[i++]); tail = tail.next; } } tail.next = null; return head; } /** * 遍历 * @param node */ public static void Traverse(ListNode node) { while (node != null) { System.out.println(node.val); node = node.next; } }
public static void main(String[] args) { int arr[] = {1,2,3,4,5}; ListNode head = null; head = headInsert(arr); //head = tailInsert(arr); Traverse(head); }
}
|
近期评论