1.定义节点
public class ListNode { int val; ListNode next; public ListNode() { } public ListNode(int val) { this.val = val; } public ListNode(int val, ListNode next) { this.val = val; this.next = next; } }
2.操作生成链表
class MyLinkedList { int size=0; ListNode head; public MyLinkedList() { head=new ListNode(0);//长度+1,计算的时候要加上 } public int get(int index) { if(index<0||index>=size) return -1; ListNode cur=head; for(int i=0;i<=index;i++){ cur=cur.next; } return cur.val; } public void addAtHead(int val) { addAtIndex(0,val); } public void addAtTail(int val) { addAtIndex(size,val); } public void addAtIndex(int index, int val) { if(index>size)return; if(index<0)index=0; size++; ListNode pre=head; for(int i=0;i<index;i++){ pre=pre.next; } ListNode temp=new ListNode(val); temp.next=pre.next; pre.next=temp; } public void deleteAtIndex(int index) { if(index<0||index>=size)return; size--; ListNode pre=head; for(int i=0;i<index;i++){ pre=pre.next; } pre.next=pre.next.next; } }
3.合并操作
public class Solution1 { public ListNode mergeTwoLists(ListNode list1, ListNode list2) { ListNode dummy=new ListNode(-1),p=dummy; ListNode p1=list1,p2=list2; while(p1!=null&&p2!=null){ if(p1.val<p2.val){ p.next=p1; p1=p1.next; }else{ p.next=p2; p2=p2.next; } p=p.next; } if(p1!=null){ p.next=p1; } if(p2!=null){ p.next=p2; } return dummy.next; } public static void main(String[] args){ MyLinkedList list1 = new MyLinkedList(); MyLinkedList list2 = new MyLinkedList(); list1.addAtTail(1); list1.addAtTail(2); list2.addAtTail(1); list2.addAtTail(3); Solution1 solution = new Solution1(); ListNode listNode = solution.mergeTwoLists(list1.head.next, list2.head.next); while (listNode!=null){ System.out.println(listNode.val); listNode=listNode.next; } } }
标签:ListNode,val,int,合并,public,链表,节点,size From: https://www.cnblogs.com/upupup-999/p/17073964.html