当前位置: 代码迷 >> 综合 >> 链表-相关的基础算法代码总结
  详细解决方案

链表-相关的基础算法代码总结

热度:61   发布时间:2024-01-31 04:41:51.0

以代码为主,帮助自己较好的理解私思想。

1.反转链表

	//反转链表public ListNode ReverseList(ListNode head){ListNode current = head;//当前节点ListNode pre = null;ListNode reverseHead = null;//反转后的头结点ListNode temp = null;while(current != null){temp = current.next;current.next = pre;if(null == temp){reverseHead = current;break;}pre = current;current = temp;}return reverseHead;}

2.带环链表-环的入口节点(一步两步)

	//单向带环链表 环的入口节点  ---相遇肯定是在环上public ListNode EntryNodeOfLoop(ListNode pHead){if(pHead.next == null || pHead.next.next == null){//一步两步return null;}ListNode slow = pHead.next;ListNode fast = pHead.next.next;while(fast != null){if(slow == fast){//第一次相遇后(在环上)fast = pHead;while(slow != fast){slow = slow.next;fast = fast.next;}return fast;}//如果还没有第一次相遇  一步两步slow = slow.next;fast = fast.next.next;}return null;}

3.从尾至头输出链表节点值(递归)

	ArrayList<Integer> arrList = new ArrayList<Integer>();//从尾至头输出链表节点值public ArrayList<Integer> PrintListFromTailToHead(ListNode head){if(head != null){PrintListFromTailToHead(head.next);arrList.add(head.val);}return arrList;}

4.两个链表的第一个公共节点

	//两个链表的第一个公共节点public ListNode FindFirstCommonNode(ListNode pHead1,ListNode pHead2){if(pHead1 == null || pHead2 == null){return null;}int count1 = GetLength(pHead1);int count2 = GetLength(pHead2);ListNode p = pHead1;ListNode q = pHead2;if(count1 > count2){for(int i = 0;i < count1-count2;i++){//长度大的先走几步p = p.next;}while(p != q){p = p.next;q = q.next;}}else if(count1 < count2){for(int j = 0;j < count2-count1;j++){q = q.next;}while(p != q){p = p.next;q = q.next;}}else{while(p != q){p = p.next;q = q.next;}}return p;}public int GetLength(ListNode pHead){//获取链表长度int count = 0;while(pHead != null){count++;pHead = pHead.next;}return count;}

5.链表的倒数第K个节点

	//链表的倒数第K个节点public ListNode FindKthToTail(ListNode head,int k){//k的值从1开始if(head == null || k <= 0){return null;}ListNode p = head;ListNode q = head;for(int i = 1;i < k;i++){//p先走if(p.next != null){p = p.next;}else{return null;}}while(p.next != null){p = p.next;q = q.next;}return q;}

链表相关,先整理这些,后续补充。

  相关解决方案