java 链表定义
public class ListNode {
int val;
ListNode next;
public ListNode() {} /无参构造
public ListNode(int val) {
this.val = val;
}
public ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
leetcode 203
题目链接
基础算法:remove element
- 构建虚拟头结点
newHead
,这样可以使得每个节点的操作步骤同
ListNode newHead = new ListNode(-1, head);
完整代码:
class Solution {
public ListNode removeElements(ListNode head, int val) {
if (head == null)
return head;
ListNode newHead = new ListNode(-1, head);
ListNode pre = newHead;
ListNode cur = head;
while (cur != null) {
if (cur.val == val)
pre.next = cur.next;
else
pre = pre.next;
cur = cur.next;
}
return newHead.next;
}
}
leetcode 707
题目链接
链表的各类操作:插入、删除、获取值
index
从0
开始计数- 注意插入和删除时是要在
index
前操作
class ListNode {
int val;
ListNode next;
public ListNode() {}
public ListNode(int val) {
this.val = val;
}
public ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
class MyLinkedList {
int size;
ListNode head; //虚拟头结点
public MyLinkedList() {
head = new ListNode(-1);
size = 0;
}
public int get(int index) {
if (index >= size || index < 0)
return -1;
ListNode cur = head;
while (index -- >= 0) {
cur = cur.next;
}
return cur.val;
}
public void addAtHead(int val) {
addAtIndex(0, val);
}
public void addAtTail(int val) {
addAtIndex(size, val);
}
public void addAtIndex(int index, int val) {
if (index > size)
return;
//if (index < 0)
++size;
ListNode cur = head;
while(index -- > 0) { //找到Index-1元素
cur = cur.next;
}
ListNode node = new ListNode(val, cur.next);
cur.next = node;
}
public void deleteAtIndex(int index) {
if (index >= size || index < 0)
return;
--size;
//删除头节点
if (index == 0) {
head = head.next;
return;
}
ListNode cur = head;
while (index -- > 0) { //找到Index-1元素
cur = cur.next;
}
cur.next = cur.next.next;
}
}
/**
* Your MyLinkedList object will be instantiated and called as such:
* MyLinkedList obj = new MyLinkedList();
* int param_1 = obj.get(index);
* obj.addAtHead(val);
* obj.addAtTail(val);
* obj.addAtIndex(index,val);
* obj.deleteAtIndex(index);
*/
leetcode206
题目链接
经典题目:reverse Linked List
思路:
- 双指针法:用两个指针指向连续的两个元素,然后修改
next
指向 - 递归法:终止条件就是双指针判断时
前指针!=null
条件
双指针法
时间复杂度O(n)
空间复杂度O(1)
class Solution {
public ListNode reverseList(ListNode head) {
ListNode p = null;
ListNode q = head;
while (q != null) {
ListNode t = q.next;
q.next = p;
p = q;
q = t;
}
return p;
}
}
递归法
时间复杂度O(n)
空间复杂度O(n)
- 递归调用,用栈存储
class Solution {
public ListNode reverse(ListNode p, ListNode q) {
if (q == null) //终止条件
return p;
ListNode t = q.next;
q.next = p;
return reverse(q, t);
}
public ListNode reverseList(ListNode head) {
return reverse(null, head);
}
}