Java链表实现
说是实现链表,其实实现的是一个个的链表节点。
public class ListNode {
public ListNode next;
public int val;
public ListNode(int val){
this.val = val;
}
}
实现将一个数组插入成为一个链表
public static ListNode CreateLinkedList(int[] nums){
ListNode head = new ListNode(0);
ListNode dummy = head;
for(int i=0; i<nums.length; i++){
dummy.next = new ListNode(nums[i]);
dummy = dummy.next;
}
return head.next;
}
遍历链表
public static void Traverse(ListNode node){
ListNode dummy = new ListNode(0);
dummy.next = node;
while(dummy.next != null){
if(dummy.next.next!=null){
System.out.print(dummy.next.val+"->");
}
else {
System.out.print(dummy.next.val);
}
dummy = dummy.next;
}
return;
}
链表逆序,我的第一种方法:链表外操作
public static ListNode reverse(ListNode head){
if(head == null || head.next == null) return head;
ListNode dummy = head, dummy2 = new ListNode(head.val);
while(dummy.next!=null){
ListNode tmp = new ListNode(dummy.next.val);
tmp.next = dummy2;
dummy2 = tmp;
dummy = dummy.next;
}
return dummy2;
}
链表逆序,我的第二种方法:链表内操作
public static ListNode reverse2(ListNode head){
if(head==null || head.next==null) return head;
ListNode back = null;
while(head.next!=null){
ListNode front = head.next;
head.next = back;
back = head;
head = front;
if(head.next == null){
head.next = back;
break;
}
}
return head;
}
测试代码:
public static void main(String[] args) {
int[] nums = {1,3,5,3,7,5};
ListNode head = CreateLinkedList(nums);
Traverse(head);
System.out.println(" ");
Traverse(reverse(head));
System.out.println(" ");
Traverse(reverse2(head));
return;
}
运行结果
1->3->5->3->7->5
5->7->3->5->3->1
5->7->3->5->3->1
Process finished with exit code 0