链表相关
1.链表反向打印
1 public static void printNode(ListNode pHead){ 2 /* 3 采用栈来从尾到头打印链表 4 Stack<Integer> stack=new Stack<>(); 5 while (pHead !=null){ 6 stack.push(pHead.val); 7 pHead=pHead.next; 8 } 9 while (!stack.isEmpty()){ 10 System.out.println(stack.pop()); 11 }*/ 12 采用递归的形式打印 13 if(pHead !=null){ 14 if(pHead.next !=null){ 15 printNode(pHead.next); 16 } 17 System.out.println(pHead.val); 18 } 19 }
2.链表反转
1 public static ListNode reverseList(ListNode pHead){ 2 ListNode preNode=null; 3 ListNode pNode=pHead; 4 ListNode res=null; 5 if(pHead==null){ 6 return res; 7 } 8 while (pNode !=null){ 9 ListNode nNode=pNode.next; 10 if (nNode == null) { 11 res=pNode; 12 } 13 pNode.next=preNode; 14 preNode=pNode; 15 pNode=nNode; 16 } 17 return res; 18 }
3.查找链表倒数第K个节点的值
1 public static int findKNode(ListNode pHead,int k){ 2 ListNode fast=pHead; ListNode slow=pHead; 3 ListNode pNode=pHead; 4 if(pHead==null || k<=0){ 5 return -1; 6 } 7 for(int i=0;i<k;i++){ 8 if(fast.next !=null){ //用于判断k是否大于链表节点总数 9 fast=fast.next; 10 }else { 11 return -1; 12 } 13 } 14 while (fast !=null){ 15 fast=fast.next; 16 slow=slow.next; 17 } 18 return slow.val; 19 }
4.判断链表是否成环
1 public static int findMiddleNode(ListNode pHead){ 2 ListNode fast=pHead; 3 ListNode slow=pHead; 4 ListNode pNode=pHead; 5 if(pHead==null){ 6 return -1; 7 } 8 while (fast.next !=null){ 9 fast=fast.next.next; 10 slow=slow.next; 11 } 12 return slow.val; 13 }
5.合并两个排序的链表
1 public static ListNode mergeList(ListNode pHead1,ListNode pHead2){ 2 if(pHead1==null){ 3 return pHead2; 4 } 5 if (pHead2 == null) { 6 return pHead1; 7 } 8 ListNode res=null; 9 if(pHead1.val<pHead2.val){ 10 res=pHead1; 11 res.next=mergeList(pHead1.next,pHead2); 12 }else { 13 res=pHead2; 14 res.next=mergeList(pHead1,pHead2.next); 15 } 16 return res; 17 }