zoukankan      html  css  js  c++  java
  • Linked List链表类题目的解题模板

    B站图灵星球的视频总结的文档,传送门
    基本都是双指针法,一个移动快,一个移动慢。

    定义

     public class ListNode {
    	 int val;
     	 ListNode next;
     	 ListNode(int x){ val = x; }
    	 }
    

    1. Linked List找中间节点

    两个指针同向而行,一个每次前进2个节点,另一个每次前进1个节点,当快指针到最后,慢指针就停留在中点。

    public ListNode LinkedListMiddleNode (ListNode head){
    	ListNode i = head; 
        ListNode j = head;
    	while(j != null && j.next != null){
    		i = i.next;
    		j = j.next.next;
    	}
    	return i;
        }
    

    2. Linked List找倒数第K个节点(LeetCode面试题02.02)

    先使两个指针相隔K个位置,然后使每次以相同的速度向前移动,当快指针出界时候,慢指针就停留在倒数第K个位置

    public ListNode LinkedListLastKthNode(ListNode head,int k){ 
        ListNode i = head;
        ListNode j = head;
        for(int a = 0; a < k; a++){ 
            j = j.next; //使i和j相隔K个节点
        }
        while(j != null){ 
            i = i.next;
            j = j.next; 
        }
            return i; 
    } 
    

    3. 反转链表(LeetCode面试题24)

    可以使用递归或者迭代。
    1->2->3->4->5反转后变为1<-2<-3<-4<-5

    public ListNode reverse(ListNode head){ 
        if(head == null || head.next == null){ 
            return head; 
            ListNode reversed_head = reverse(head.next); 
            head.next.next = head; 
            head.next = null; 
            return reversed_head;
        }
    }
    
  • 相关阅读:
    Input file 调用相机
    C#读取txt文件
    高并发下获取随机字符串
    将Datatable转换为Json数据
    System.IO.Path 获得文件的后缀名
    用Js写的贪吃蛇游戏
    C#中的事件
    通过一个控制台小Demo--算术题,来展示C#基本的程序结构
    数据库高级应用之游标
    数据库高级应用之事务
  • 原文地址:https://www.cnblogs.com/GEMyd/p/13156270.html
Copyright © 2011-2022 走看看