当前位置:网站首页>Li Kou brush question diary /day7/2022.6.29
Li Kou brush question diary /day7/2022.6.29
2022-07-04 18:23:00 【Bobo toilet cleaning spirit】
Java Linked list basic learning
Java Class constructor
A constructor is a special method of a class , A new object used to initialize a class , Creating objects (new Operator ) And then automatically call .Java Each class in has a default constructor , And there can be more than one construction method .
Java The construction method has the following characteristics :
The method name must be the same as the class name
There can be 0 individual 、1 Two or more parameters
No return value , Include void
The default return type is the object type itself
Only with new Operators are used in conjunction with
The construction method cannot be static、final、synchronized、abstract and native( Be similar to abstract) modification .
public class MyClass {
private int m; // Define private variables
MyClass() {
// Define the construction method without parameters
m = 0;
}
MyClass(int m) {
// Define a construction method with parameters
this.m = m;
}
}
// Here are leetcode Source code on ,
// Notes are the review of knowledge points of class structure
* public class ListNode {
* int val; // Node values
* ListNode next; //ListNode Type a pointer , Point to next node
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
// use java Define the linked list structure of the implementation ,ListNode It's essentially a java class , Have the characteristics of a class , Create objects ; Access the member variables and member methods of the class through objects
//ListNode There are three construction methods in , The constructor and class name must be the same
// Yes, of course ,ListNode There are also generics , Using generics can be compatible with different data types
class ListNode<E>{ // Class name :Java Class is a custom data structure
E val; // data : Node data
ListNode<E> next; // object : Reference the next node object . stay Java There is no concept of pointer in ,Java And C Language pointers are similar to
ListNode(E val){ // Construction method : The construction method is the same as the class name
this.val=val; // Assign the received parameter to the current class val Variable
}
}
java Class definition plus public With or without public The difference and application of
public ListNode mergeTwoLists (){}
// Define a method , The name of the method is mergeTwoLists, The type of return value is ListNode
public calss solution{}
// Add public Represents a global class , This class can import Into any class . No addition public The default is reserved class , Can only be referenced by other classes in the same package
// It is worth noting that public class Although it can be accessed by any class , But if the method in the visited class does not add public perhaps static, There will be a warning, So when you want to access other packages public Methods in class , You need to add public perhaps static In order to access .
Example :
Recursive method :
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
if(list1 == null){
return list2;
} else if(list2 == null){
return list1;
} else if(list1.val < list2.val){
list1.next = mergeTwoLists(list1.next,list2);
return list1;
} else{
list2.next = mergeTwoLists(list2.next,list1);
return list2;
}
}
}
// The head node defaults to the first node
//list1.val=head.val
// Recursion is adopted
Ideas
We can recursively define... In two linked lists as follows merge operation ( Ignore the boundary case , For example, empty linked list ): in other words , The node with the smaller head value of the two linked lists is the same as that of the remaining elements merge Operation result merging .
Let's model the recursive process directly , At the same time, we need to consider the boundary conditions .
If l1 perhaps l2 It started with an empty list , So no operations need to be merged , So we just need to return a non empty list . otherwise , We need to judge l1 and l2 Which list's head node has a smaller value , Then recursively determine the next node to add to the result . If one of the two linked lists is empty , Recursion ends .
Iterative method :
Ideas : When list1 and list2 Is not an empty list , Judge list1 and list2 The size of the head node value of , Put smaller values in the result linked list , A node is placed in the result linked list , Move the node of the corresponding linked list backward by one bit .
Algorithm :
First set up a The sentinel node prehead(-1), After the list merging , Go straight back to prehead.next that will do , Maintain a prev The pointer ;
ListNode prev = prehead //ListNode prev Express prev The type is ListNode type ,
In the next judgment , adjustment prev Pointer position and prev The location of , If list1 Current node value (val) Less than list2 Node value , hold list1 The current node is connected to prev After the node (prev.next=list1), meanwhile list1 Move the pointer back one bit (list1=list1.next), otherwise , Yes list2 Make the same change . No matter how we move list1,list2 Pointer position of ,prev All positions should be moved backward (prev=prev.next)
At the end of the cycle , l1 and l2 At most one is not empty . Because the two input lists are ordered , So no matter which list is not empty , It contains all the elements larger than all the elements in the previously merged linked list . This means that we just need to simply connect the non empty list to the back of the merged list , And return to the merge list .
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode prehead = new ListNode(-1); // The sentinel node
ListNode prev = prehead;
while (l1 != null && l2 != null) {
if (l1.val <= l2.val) {
prev.next = l1;
l1 = l1.next;
} else {
prev.next = l2;
l2 = l2.next;
}
prev = prev.next;
}
// After the merger l1 and l2 At most, only one has not been merged yet , We can directly point the end of the linked list to the list that has not been merged
prev.next = l1 == null ? l2 : l1;
return prehead.next;
}
}
边栏推荐
- ITSS运维能力成熟度分级详解|一文搞清ITSS证书
- 【Go语言刷题篇】Go完结篇|函数、结构体、接口、错误入门学习
- Pytoch deep learning environment construction
- Superscalar processor design yaoyongbin Chapter 7 register rename excerpt
- Lua EmmyLua 注解详解
- [daily question] 556 Next bigger element III
- celebrate! Kelan sundb and Zhongchuang software complete the compatibility adaptation of seven products
- 【211】go 处理excel的库的详细文档
- Large scale service exception log retrieval
- SIGMOD’22 HiEngine论文解读
猜你喜欢
【Go语言刷题篇】Go完结篇|函数、结构体、接口、错误入门学习
Weima, which is going to be listed, still can't give Baidu confidence
12 - explore the underlying principles of IOS | runtime [isa details, class structure, method cache | t]
Neglected problem: test environment configuration management
为啥有些线上演唱会总是怪怪的?
Easy to use map visualization
Stars open stores, return, return, return
创业两年,一家小VC的自我反思
删除二叉搜索树中的节点附图详解
TCP waves twice, have you seen it? What about four handshakes?
随机推荐
TCP waves twice, have you seen it? What about four handshakes?
估值900亿,超级芯片IPO来了
Pytorch深度学习之环境搭建
2022年全国CMMI认证补贴政策|昌旭咨询
蓝桥:合根植物
Achieve animation effect through event binding
【209】go语言的学习思想
Flask lightweight web framework
Implementation of shell script replacement function
比李嘉诚还有钱的币圈大佬,刚在沙特买了楼
[system analyst's road] Chapter 7 double disk system design (structured development method)
股价大跌、市值缩水,奈雪推出虚拟股票,深陷擦边球争议
With the stock price plummeting and the market value shrinking, Naixue launched a virtual stock, which was deeply in dispute
Analysis of I2C adapter driver of s5pv210 chip (i2c-s3c2410. C)
Face_recognition人脸识别之考勤统计
【Hot100】31. Next spread
MySQL common add, delete, modify and query operations (crud)
[test development] software testing - Basics
Reptile elementary learning
Android uses sqliteopenhelper to flash back