Linked List
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Java Variables & Data Types
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Java Variable & Data Types
- Primitive Type
- int a = 5;
- byte, short, int, long, float, double, char, boolean
- ONLY these eight types.
- Reference Type
- String str = new String("this is a string");
- String, int[], MyObject, ..., etc.
- new & array.
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Memory
Heap Memory
Stack Memory
Java Variable & Data Types
- Primitive Type - Stack Memory
- Reference Type - Heap Memory
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Variable Define - Primitive
- Primitive Type
- Store the value directly.
- Reference Type
- Store the address of the real object.
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Variable Define - Primitive
- int a = 5
Memory
Heap Memory
Stack Memory
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Variable Define - Primitive
- int a = 5
- Store the value 5 directly in the stack memory
Memory
Heap Memory
Stack Memory
5
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Variable Define - Primitive
- int a = 5
- Store the value 5 directly in the stack memory
- Give 5 an alias, 'a'
Memory
Heap Memory
Stack Memory
5
a
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Variable Define - Reference
- MyObject obj = new MyObject();
Memory
Heap Memory
Stack Memory
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Variable Define - Reference
- MyObject obj;
- obj = new MyObject();
Memory
Heap Memory
Stack Memory
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Variable Define - Reference
- MyObject obj;
- obj = new MyObject();
Memory
Heap Memory
Stack Memory
obj
?
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Variable Define - Reference
- MyObject obj;
- obj = new MyObject();
Memory
Heap Memory
Stack Memory
MyObject instance
obj
?
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Variable Define - Reference
- MyObject obj;
- obj = new MyObject();
Memory
Heap Memory
Stack Memory
MyObject instance
obj
addr1
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Variable Define - Reference
- MyObject obj = new MyObject();
- Date date = new Date(1, 1, 2016);
Memory
Heap Memory
Stack Memory
MyObject instance
addr1
obj
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Variable Define - Reference
- MyObject obj = new MyObject();
- Date date = new Date(1, 1, 2016);
Memory
Heap Memory
Stack Memory
MyObject instance
addr1
obj
1 |
---|
1 |
2016 |
Date instance
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Variable Define - Reference
- MyObject obj = new MyObject();
- Date date = new Date(1, 1, 2016);
Memory
Heap Memory
Stack Memory
MyObject instance
addr1
obj
1 |
---|
1 |
2016 |
addr2
Date instance
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Variable Define - Reference
- MyObject obj = new MyObject();
- Date date = new Date(1, 1, 2016);
Memory
Heap Memory
Stack Memory
MyObject instance
addr1
obj
1 |
---|
1 |
2016 |
addr2
date
Date instance
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Variable Assignment - Primitive
- Primitive Type
- Assign the value of RHS to the LHS.
- Reference Type
- Assign the address of RHS object to the LHS.
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Variable Assignment - Primitive
- int a = 5;
- int b = a; // a = 5, b = 5
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Variable Assignment - Primitive
- int a = 5;
- int b = a;
- b = 4; // a = 5, b = 4
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Variable Assignment - Primitive
- int a = 5;
- int b = a;
- b = 4; // a = 5, b = 4
- No mater how you assign a with b, or assign a/b with another value
- changing one of them, will NOT affect the other one.
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Variable Assignment - Reference
- MyObject obj1 = new MyObject();
Memory
Heap Memory
Stack Memory
MyObject instance
addr1
obj1
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Variable Assignment - Reference
- MyObject obj1 = new MyObject();
- MyObject obj2 = obj1; // obj1 and obj2 points to the same object instance.
Memory
Heap Memory
Stack Memory
MyObject instance
addr1
obj1
obj2
addr1
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Variable Assignment - Reference
- MyObject obj1 = new MyObject();
- MyObject obj2 = obj1; // obj1 and obj2 point to the same object instance. Changing the field of one will affect the other
- // Suppose obj1 has a field 'a', its value is 5
- obj2.a = 4; // obj1.a = 4
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Variable Assignment - Reference
- MyObject obj1 = new MyObject();
- MyObject obj2 = obj1;
- obj2 = new MyObject();
Memory
Heap Memory
Stack Memory
MyObject instance
addr1
obj1
obj2
addr2
MyObject instance
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Variable Assignment - Reference
- MyObject obj1 = new MyObject();
- MyObject obj2 = obj1;
- obj2 = new MyObject();
- // obj1 and obj2 point to different objects. Changing one will not affect the other.
- // Suppose obj1 has field 'a', and its value is 5.
- obj2.a = 3; // obj1.a = 5
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Variable Comparison
- Primitive Type
- Compare the value of the variable.
- int a = 5;
- int b = 5; // a == b ? True
- Reference Type
- Compare the address of the object.
- MyObject obj1 = new MyObject();
- MyObject obj2 = obj1; // obj1 == obj2 ? True
- obj2 = new MyObject(); // obj1 == obj2 ? False
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Variable Comparison
Copyright © 直通硅谷
http://www.zhitongguigu.com/
String a = "abc";
String b = "abc";
System.out.println(a == b); // true
String c = new String("abc");
System.out.println(a == c); // false
System.out.println(a.equals(c)); // trye
String d = new String("abc");
System.out.println(c == d); // false
System.out.println(d.equals(c)); // true
Integer num1 = 1;
Integer num2 = 1;
System.out.println(num1 == num2); // true
Integer num3 = new Integer(1);
System.out.println(num1 == num3); // false
Integer num4 = new Integer(1);
System.out.println(num3 == num4); // false
System.out.println(num3.equals(num4)); // true
// OPTIONAL OPTIONAL******
Integer num5 = new Integer(0);
System.out.println(num3 == num4+num5); // true
Use equals function for reference comparison
Passing Parameters
- Primitive Type
- Passing the COPY of primitive value.
- Reference Type
- Passing the COPY of object address.
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Passing Parameters
- Primitive Type
- Passing the copy of primitive value.
public void increase(int a) {
a = a + 1;
System.out.print(a);
}
public static void main() {
int a = 5;
increase(a);
System.out.print(a);
}
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Passing Parameters
- Primitive Type
- Passing the copy of primitive value.
public void increase(int a) {
a = a + 1;
System.out.print(a);
}
public static void main() {
int a = 5;
increase(a); // print 6.
System.out.print(a); // print 5
}
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Passing Parameters
- Primitive Type
- Passing the copy of primitive value.
- The original variable will NEVER be changed.
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Passing Parameters
- Reference Type
- Passing the copy of object address.
public void increase(MyObject obj) {
obj.a += 1;
System.out.print(obj.a);
}
public static void main() {
MyObject obj = new MyObject();
obj.a = 5;
increase(obj);
System.out.print(obj.a);
}
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Passing Parameters
- Reference Type
- Passing the copy of object address.
public void increase(MyObject obj) {
obj.a += 1;
System.out.print(obj.a);
}
public static void main() {
MyObject obj = new MyObject();
obj.a = 5;
increase(obj); // print 6.
System.out.print(obj.a); // print 6
}
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Passing Parameters
- Reference Type
- Passing the copy of object address.
- Changing the object (parameter) inside the function WILL change the original object.
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Passing Parameters
- Reference Type
- Passing the copy of object address.
public void increase(MyObject obj) {
MyObject obj2 = obj;
obj2.a += 1;
System.out.print(obj.a);
System.out.print(obj2.a);
}
public static void main() {
MyObject obj = new MyObject();
obj.a = 5;
increase(obj);
System.out.print(obj.a);
}
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Passing Parameters
- Reference Type
- Passing the copy of object address.
public void change(String str) {
str = new String("world");
System.out.print(str);
}
public static void main() {
String s = new String("hello");
change(s); // print 'world';
System.out.print(s); // print 'hello'.
}
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Passing Parameters
- Reference Type
- Passing the copy of object address.
public void increase(MyObject obj) {
MyObject obj2 = obj;
obj2.a += 1;
System.out.print(obj.a);
System.out.print(obj2.a);
}
public static void main() {
MyObject obj = new MyObject();
obj.a = 5;
increase(obj); // print 6, then print 6.
System.out.print(obj.a);
}
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Passing Parameters
- Reference Type
- Passing the copy of object address.
public void increase(MyObject obj) {
MyObject obj2 = obj;
obj2.a += 1;
System.out.print(obj.a);
System.out.print(obj2.a);
}
public static void main() {
MyObject obj = new MyObject();
obj.a = 5;
increase(obj); // print 6, then print 6.
System.out.print(obj.a); // print 6.
}
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Java Data Type Summary
- Primitive Type
- Always means a literal value, such as 5, 's', true, etc.
- Reference Type
- Always means an address.
- ... = new Object();
- ... = obj;
- myFunction(obj);
Address of the real object.
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Linked List
Copyright © 直通硅谷
http://www.zhitongguigu.com/
What is Linked List?
A data structure consisting of a linear collection of data elements, called nodes pointing to the next node by means of pointer.
Copyright © 直通硅谷
http://www.zhitongguigu.com/
1
3
8
4
5
2
Copyright © 直通硅谷
http://www.zhitongguigu.com/
1 | 4 | 8 | 2 | 5 | 3 |
---|
Copyright © 直通硅谷
http://www.zhitongguigu.com/
1 | 4 | 8 | 2 | 5 | 3 |
---|
1
3
8
4
5
2
Copyright © 直通硅谷
http://www.zhitongguigu.com/
1 | 4 | 8 | 2 | 5 | 3 |
---|
1
3
8
4
5
2
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Linked List
- Each node knows the address of its next node.
- The first node can represent the whole linked list.
- Accessing any element in the linked list, needs going through all nodes before it. O(n).
- Sometimes, the node also knows the address of its previous node, then the list is known as "Doubly Linked List".
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Linked List in Code
public class ListNode {
int val;
ListNode next;
ListNode(int val_) {
val = val_;
next = null; // this line is optional
}
}
public class LinkedList {
ListNode head;
ListNode tail;
int size;
}
Copyright © 直通硅谷
http://www.zhitongguigu.com/
WHY use linked list?
For most cases, the size of memory needed CANNOT be known before.
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Basic Operations
- Get: <index> ---> value, O(n)
- Set: <index, value> ---> void (new LinkedList), O(n)
- Add: <opt_index, value> ---> void (new LinkedList), O(n)
- Remove: <index/value> ---> void (new LinkedList), O(n)
Copyright © 直通硅谷
http://www.zhitongguigu.com/
How to implement LinkedList
public class LinkedList{
// TODO: implement this class.
public int get(int index);
public void set(int index, int value);
public void add(int index, int value);
public void remove(int index);
public void removeByValue(int value);
}
public class ListNode {
int val;
ListNode next;
public ListNode(int val_) {
this.val = val_;
}
}
Copyright © 直通硅谷
http://www.zhitongguigu.com/
How to implement LinkedList - Fields
public class LinkedList{
private ListNode head;
private ListNode tail;
private int size;
public LinkedList() {
head = null;
tail = null;
size = 0;
}
}
Java will automatically initialize the value for the fields.
Copyright © 直通硅谷
http://www.zhitongguigu.com/
How to implement LinkedList - Fields
public class LinkedList{
private ListNode head;
private ListNode tail;
private int size;
public LinkedList() {
}
}
Java will automatically generate a non-param constructor if you don't have other constructors.
Copyright © 直通硅谷
http://www.zhitongguigu.com/
How to implement LinkedList - Fields
public class LinkedList{
private ListNode head;
private ListNode tail;
private int size;
}
Java will automatically generate a non-param constructor if you don't have other constructors.
Copyright © 直通硅谷
http://www.zhitongguigu.com/
How to implement LinkedList - Fields
public class LinkedList{
private ListNode head = null;
private ListNode tail = null;
private int size = 0;
}
Recommend !!!
Copyright © 直通硅谷
http://www.zhitongguigu.com/
How to implement LinkedList - Get
public class LinkedList{
public void checkBoundsExclusive(int index) {
if (index < 0 || index >= size) {
// throw Exception.
}
}
public ListNode getEntry(int index) {
ListNode cur = head;
for (int i = 0; i < index; i++) {
cur = cur.next;
}
return cur;
}
public int get(int index) {
checkBoundsExclusive(index);
return getEntry(index).val;
}
}
public ListNode getEntry(int index) {
ListNode cur = head;
while (index-- != 0) {
cur = cur.next;
}
return cur;
}
Copyright © 直通硅谷
http://www.zhitongguigu.com/
How to implement LinkedList - Set
public class LinkedList{
public void set(int index, int value) {
checkBoundsExclusive(index);
Listnode node = getEntry(index);
node.val = value;
}
}
Copyright © 直通硅谷
http://www.zhitongguigu.com/
How to implement LinkedList - Add
public class LinkedList{
public void add(int index, int value) {
checkBoundsExclusive(index);
ListNode newNode = new ListNode(value);
ListNode pre = getEntry(index-1);
newNode.next = pre.next;
pre.next = newNode;
}
}
Copyright © 直通硅谷
http://www.zhitongguigu.com/
How to implement LinkedList - Add
public class LinkedList{
public void add(int index, int value) {
checkBoundsExclusive(index);
ListNode newNode = new ListNode(value);
if (index == 0) {
newNode.next = head;
head = newNode;
return;
}
ListNode pre = getEntry(index-1);
newNode.next = pre.next;
pre.next = newNode;
}
}
Copyright © 直通硅谷
http://www.zhitongguigu.com/
How to implement LinkedList - Remove
public class LinkedList{
public void remove(int index) {
checkBoundsExclusive(index);
ListNode pre = getEntry(index-1);
pre.next = pre.next.next;
}
}
Copyright © 直通硅谷
http://www.zhitongguigu.com/
How to implement LinkedList - Remove
public class LinkedList{
public void remove(int index) {
checkBoundsExclusive(index);
if (index == 0) {
head = head.next;
return;
}
ListNode pre = getEntry(index-1);
pre.next = pre.next.next;
}
}
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Why need special case
Because head node is different
Copyright © 直通硅谷
http://www.zhitongguigu.com/
null
There is no node pointing at head!!!
head
Head Node is Different
Copyright © 直通硅谷
http://www.zhitongguigu.com/
null
There is no node pointing at head!!!
?
head
Head Node is Different
Copyright © 直通硅谷
http://www.zhitongguigu.com/
null
head
fake head
Head Node is Different
Copyright © 直通硅谷
http://www.zhitongguigu.com/
null
head
dummy
- dummy.next can represent original linked list.
- head node will have a previous node.
- head node is NOT different any more.
Head Node is Different
Copyright © 直通硅谷
http://www.zhitongguigu.com/
How to implement LinkedList - Add
public class LinkedList{
public void add(int index, int value) {
checkBoundsExclusive(index);
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode pre = dummy;
while (index-- != 0) {
pre = pre.next;
}
ListNode newNode = new ListNode(value);
newNode.next = pre.next;
pre.next = newNode;
head = dummy.next;
}
}
Copyright © 直通硅谷
http://www.zhitongguigu.com/
How to implement LinkedList - Add
public class LinkedList{
public void add(int index, int value) {
checkBoundsExclusive(index);
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode pre = dummy;
while (index-- != 0) {
pre = pre.next;
}
ListNode newNode = new ListNode(value);
newNode.next = pre.next;
pre.next = newNode;
head = dummy.next;
}
}
ListNode pre = getEntry(index-1);
Copyright © 直通硅谷
http://www.zhitongguigu.com/
How to implement LinkedList - Add
public class LinkedList{
public void add(int index, int value) {
checkBoundsExclusive(index);
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode pre = dummy;
while (index--) {
pre = pre.next;
}
ListNode newNode = new ListNode(value);
newNode.next = pre.next;
pre.next = newNode;
head = dummy.next;
}
}
ListNode pre = head;
index = index - 1;
while (index-- != 0) {
pre = pre.next;
}
Copyright © 直通硅谷
http://www.zhitongguigu.com/
How to implement LinkedList - Add
public class LinkedList{
public void add(int index, int value) {
checkBoundsExclusive(index);
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode pre = dummy;
while (index-- != 0) {
pre = pre.next;
}
ListNode newNode = new ListNode(value);
newNode.next = pre.next;
pre.next = newNode;
head = dummy.next;
}
}
public class LinkedList{
public void add(int index, int value) {
checkBoundsExclusive(index);
ListNode newNode = new ListNode(value);
if (index == 0) {
newNode.next = head;
head = newNode;
return;
}
ListNode pre = head;
index = index - 1;
while (index-- != 0) {
pre = pre.next;
}
newNode.next = pre.next;
pre.next = newNode;
}
}
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Dummy Node
- Make head node not different any more.
- Simplify edge case situation.
- Make code SHORTER.
- shorter is better.
- FEWER mistakes.
- Make code SHORTER.
- There will always exist AT LEAST ONE node, but the linked list starts from dummy's next.
Copyright © 直通硅谷
http://www.zhitongguigu.com/
How to implement LinkedList - Remove
public class LinkedList{
public void remove(int index) {
checkBoundsExclusive(index);
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode pre = dummy;
while (index-- != 0) {
pre = pre.next;
}
pre.next = pre.next.next;
head = dummy.next;
}
}
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Summary for Linked List
- Get
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Summary for Linked List
- Get
- Add
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Summary for Linked List
- Get
- Add
- Remove
Copyright © 直通硅谷
http://www.zhitongguigu.com/
- If data structure of the linkedlist will be changed, dummy node is needed.
- add, remove.
- One node can only be accessed by its previous node.
- Don't change the previous code's next before this node is assigned to a new node, unless it's useless.
Summary for Linked List
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Linked List in interview
- For most cases, there will only one head node given.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseList(ListNode head) {
}
}
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Linked List in interview
- For most cases, there will only one head node given.
- No size.
- Check null when using while.
- while (cur != null) { // do something }
- while (pre.next != null) { // do something }
- Communication before you write code !!!
- size, index range, tail, etc.
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Exercises
public class ListNode {
int val;
ListNode next;
public ListNode(int val) {
this.val = val;
}
}
Copyright © 直通硅谷
http://www.zhitongguigu.com/
- Linked list length.
- Kth node from the end.
- Mid node of the list.
- Whether circle exists.
Count Related
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Linked List Length
public int length(ListNode head) {
ListNode cur = head;
int length = 0;
while (cur != null) {
length++;
cur = cur.next;
}
return length;
}
Given a linked list, return the length of it.
Examples:
Input: 1->4->2->3
Output: 4
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Kth node from the end
Given a linked list, return the kth node from the end. Linked list will never be empty and k will always be valid.
Examples:
Input: 1->4->2->3, 2
Output: 2
Input: 3->5->9->6->8, 3
Output: 9
Copyright © 直通硅谷
http://www.zhitongguigu.com/
public ListNode kthNodeFromEnd(
ListNode head, int k) {
int length = length(head);
int index = length - k;
ListNode cur = head;
int count = 0;
while (count < index) {
cur = cur.next;
count++;
}
return cur;
}
Kth node from the end
public ListNode kthNodeFromEnd(
ListNode head, int k) {
int length = length(head);
int index = length - k;
ListNode cur = head;
while (index-- != 0) {
cur = cur.next;
}
return cur;
}
Given a linked list, return the kth node from the end. Linked list will never be empty and k will always be valid.
Examples:
Input: 1->4->2->3, 2
Output: 2
Input: 3->5->9->6->8, 3
Output: 9
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Kth node from the end
public ListNode kthNodeFromEnd(
ListNode head, int k) {
ListNode first = head;
while (k-- != 0) {
first = first.next;
}
ListNode second = head;
while (first != null) {
first = first.next;
second = second.next;
}
return second;
}
Given a linked list, return the kth node from the end. Linked list will never be empty and k will always be valid.
Examples:
Input: 1->4->2->3, 2
Output: 2
Input: 3->5->9->6->8, 3
Output: 9
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Middle Node
public ListNode midNode(ListNode head) {
int length = length(head);
int index = (length - 1) / 2;
ListNode cur = head;
while (index-- != 0) {
cur = cur.next;
}
return cur;
}
Given a linked list, return the middle node. Linked list will never be empty.
Examples:
Input: 1->4->2->3
Output: 4
Input: 3->5->9->6->8
Output: 9
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Middle Node
public ListNode midNode(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while (fast.next != null &&
fast.next.next != null) {
fast = fast.next.next;
slow = slow.next;
}
return slow;
}
Given a linked list, return the middle node. Linked list will never be empty.
Examples:
Input: 1->4->2->3
Output: 4
Input: 3->5->9->6->8
Output: 9
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Linked List Cycle
public boolean hasCycle(ListNode head) {
if (head == null) {
return false;
}
ListNode fast = head;
ListNode slow = head;
while (fast != null) {
if (fast.next == null) {
return false;
}
if (fast.next == slow) {
return true;
}
fast = fast.next.next;
slow = slow.next;
}
return false;
}
Given a linked list, define if there is a cycle in it.
Examples:
Input: 1->4->2->3
Output: false.
Input: 3->5->9->3(original)
Output: true
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Linked List Cycle - Follow up
Given a linked list, return the node where the cycle begins or null.
Examples:
Input: 1->4->2->3
Output: null.
Input: 3->5->9->3(original)
Output: 3
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Linked List Cycle - Follow up
Given a linked list, return the node where the cycle begins or null.
Examples:
Input: 1->4->2->3
Output: null.
Input: 3->5->9->3(original)
Output: 3
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Linked List Cycle - Follow up
Given a linked list, return the node where the cycle begins or null.
Examples:
Input: 1->4->2->3
Output: null.
Input: 3->5->9->3(original)
Output: 3
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Linked List Cycle - Follow up
Given a linked list, return the node where the cycle begins or null.
Examples:
Input: 1->4->2->3
Output: null.
Input: 3->5->9->3(original)
Output: 3
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Linked List Cycle - Follow up
Given a linked list, return the node where the cycle begins or null.
Examples:
Input: 1->4->2->3
Output: null.
Input: 3->5->9->3(original)
Output: 3
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Linked List Cycle - Follow up
Given a linked list, return the node where the cycle begins or null.
Examples:
Input: 1->4->2->3
Output: null.
Input: 3->5->9->3(original)
Output: 3
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Linked List Cycle - Follow up
Given a linked list, return the node where the cycle begins or null.
Examples:
Input: 1->4->2->3
Output: null.
Input: 3->5->9->3(original)
Output: 3
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Linked List Cycle - Follow up
Given a linked list, return the node where the cycle begins or null.
Examples:
Input: 1->4->2->3
Output: null.
Input: 3->5->9->3(original)
Output: 3
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Linked List Cycle - Follow up
Given a linked list, return the node where the cycle begins or null.
Examples:
Input: 1->4->2->3
Output: null.
Input: 3->5->9->3(original)
Output: 3
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Linked List Cycle - Follow up
Given a linked list, return the node where the cycle begins or null.
Examples:
Input: 1->4->2->3
Output: null.
Input: 3->5->9->3(original)
Output: 3
Copyright © 直通硅谷
http://www.zhitongguigu.com/
k
l1
l2
2 *(k+l1) = k + l1 + l2 + l1
=> k = l2
Linked List Cycle - Follow up
public ListNode detectCycle(ListNode head) {
ListNode fast = head, slow = head;
while (fast != null && slow != null) {
if (fast.next != null) {
fast = fast.next.next;
} else {
return null;
}
slow = slow.next;
if (fast == slow) {
ListNode temp = head;
while (temp != slow) {
temp = temp.next;
slow = slow.next;
}
return slow;
}
}
return null;
}
Given a linked list, return the node where the cycle begins or null.
Examples:
Input: 1->4->2->3
Output: null.
Input: 3->5->9->3(original)
Output: 3
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Exercise Summary 1.
- head == null?
- k ? compare(k, length) && compare(k, 0) && range(k): nothing.
- Null Pointer Exception
- while (node != null)
- node.next
node.next.next
- while (node != null)
-
Test Cases
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Structure Related
- Remove Duplicate from Sorted List
- Merge Sorted List
- Reverse Linked List
- Swap Nodes in Pairs
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Remove Duplicate
public ListNode removeDuplicates(
ListNode head) {
if (head == null) {
return null;
}
ListNode pre = head;
while (pre.next != null) {
if (pre.val == pre.next.val) {
pre.next = pre.next.next;
} else {
pre = pre.next;
}
}
return head;
}
Given a sorted linked list, remove all duplicates such that each element appear only once.
Examples:
Input: 1->2->2->2->3->3
Output: 1->2->3
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Remove Duplicate - Follow up
public ListNode removeDuplicates(ListNode head) {
if (head == null) {
return null;
}
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode pre = dummy;
while (pre.next != null && pre.next.next != null) {
if (pre.next.val == pre.next.next.val) {
int lastVal = pre.next.val;
while (pre.next != null && pre.next.val == lastVal) {
pre.next = pre.next.next;
}
} else {
pre = pre.next;
}
}
return dummy.next;
}
Given a sorted linked list, remove all nodes that have duplicate numbers leaving only the distinct numbers from the original list.
Examples:
Input: 1->2->2->2->3->3
Output: 1
Input: 3->4->4->5->6
Output: 3->5->6
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Merge Sorted List
Merge two sorted list and return it as a new list.
Examples:
Input: 1->2->2->2, -1->3->4->5
Output: -1->1->2->2->2->3->4->5
public ListNode merge(ListNode head1, ListNode head2) {
ListNode dummy = new ListNode(-1);
ListNode cur = dummy;
while (head1 != null && head2 != null) {
if (head1.val < head2.val) {
cur.next = new ListNode(head1.val);
head1 = head1.next;
} else {
cur.next = new ListNode(head2.val);
head2 = head2.next;
}
cur = cur.next;
}
while (head2 != null) {
cur.next = new ListNode(head2.val);
head2 = head2.next;
cur = cur.next;
}
while (head1 != null) {
cur.next = new ListNode(head1.val);
head1 = head1.next;
cur = cur.next;
}
return dummy.next;
}
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Merge Sorted List
Merge two sorted list and return it as a new list.
Examples:
Input: 1->2->2->2, -1->3->4->5
Output: -1->1->2->2->2->3->4->5
Copyright © 直通硅谷
http://www.zhitongguigu.com/
public ListNode merge(ListNode head1, ListNode head2) {
ListNode dummy = new ListNode(-1);
ListNode cur = dummy;
while (head1 != null && head2 != null) {
if (head1.val < head2.val) {
cur.next = head1;
head1 = head1.next;
} else {
cur.next = head2;
head2 = head2.next;
}
cur = cur.next;
}
if (head1 == null) {
cur.next = head2;
} else if (head2 == null) {
cur.next = head1;
}
return dummy.next;
}
Reverse Linked List
Reverse a given linked list.
Examples:
Input: 1->2->3->4
Output: 4->3->2->1
public ListNode reverse(ListNode head) {
ListNode pre = null;
ListNode cur = head;
while (cur != null) {
ListNode temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Swap Nodes in Pairs
Given a linked list, swap every two adjacent nodes and return its head.
Examples:
Input: 1->2->3->4
Output: 2->1->4->3
Note: Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Swap Nodes in Pairs
Given a linked list, swap every two adjacent nodes and return its head.
Examples:
Input: 1->2->3->4
Output: 2->1->4->3
Note: Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
Copyright © 直通硅谷
http://www.zhitongguigu.com/
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode pre = dummy;
while (pre.next != null && pre.next.next != null) {
ListNode first = pre.next, second = pre.next.next;
first.next = second.next;
second.next = first;
pre.next = second;
pre = first;
}
return dummy.next;
}
Exercise Summary 2.
- dummy.
- Structure (including head) will be changed.
- Null Pointer Exception
- while (node != null)
- node.next
- while (pre.next != null)
- pre.next, pre.next.next
- while (node != null)
-
Test Cases
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Exercise Summary 2.
- dummy.
- Structure (including head) will be changed.
- Null Pointer Exception
- while (node != null)
- node.next
- while (pre.next != null)
- pre.next, pre.next.next
- while (node != null)
-
Test Cases
while (pre.next != null && pre.next.next != null) {
if (pre.next.val == pre.next.next.val) {
int lastVal = pre.next.val;
while (pre.next != null &&
pre.next.val == lastVal) {
pre.next = pre.next.next;
}
} else {
pre = pre.next;
}
}
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Delete Node in a Linked List
Given one node in a linked list, remove that node. (Only the reference to the specific node is given).
Examples:
Input: 1->2->3->4, 3
Output: 1->2->4
public void removeNode(ListNode node) {
if (node == null) {
return;
}
if (node.next == null) {
node = null;
return;
}
node.val = node.next.val;
node.next = node.next.next;
return;
}
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Summary
- Dummy node
- Don't lose nodes
- Store the latter part before modifying the current one.
- Practice
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Homework
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Homework (Optional)
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Given two linked list (without circle), detect if they intersect with each other.
Implement:
Java: public boolean detectIntersection(ListNode head1, ListNode head2);
c++: bool detectIntersection(ListNode* head1, ListNode* head2);
Follow up: Return null or the intersection ListNode.
Java: public ListNode detectIntersection(ListNode head1, ListNode head2);
c++: ListNode* detectIntersection(ListNode* head1, ListNode* head2);
Follow up 2: What if the linked lists may have circle? Return null or the intersection node.
Homework (Optional)
Copyright © 直通硅谷
http://www.zhitongguigu.com/
[GoValley-201609] Linked List
By govalley201612
[GoValley-201609] Linked List
- 1,198