203 移除链表元素
1. 不论哪种方法,首先判断链表是不是空链表,即头节点是否存在
2. 设置虚拟头节点,指向头节点
3. 设定cur从虚拟头节点遍历,查询cur.val的值,直到cur变成null
4. while的判断条件为cur.next不为空!
5. 最后返回的是dummy.next
(好好体会cur.next)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeElements(ListNode head, int val) {
if(head==null)
return head;
ListNode dummy = new ListNode(-1,head);
ListNode cur=dummy; //永远都是cur.next是我们预处理,预操作的指针
while(cur.next!=null)
{
if(cur.next.val==val)
{
cur.next=cur.next.next; //操作cur跳过符合条件的点
}
else
{
cur=cur.next;
}
}
return dummy.next;
}
}
707 设计链表
多加了一个size属性,题目的index默认从下标开始
public class MyLinkedList
{
//声明放于类下,初始化放在构造器中
ListNode dummy;
int size;
public MyLinkedList() {
dummy = new ListNode(-1);
size=0;
}
public int get(int index) {
if(index>size-1||index<0) //下标从零开始
{
return -1;
}
//取值核心代码:cur从头节点【0】开始,
ListNode cur = dummy.next; //cur是从头节点开始
while(index>0)
{
cur=cur.next; //
index--;
}
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)
{
index=0;
}
ListNode newNode = new ListNode(val);
//要添加就要找到节点前面的位置
ListNode cur = dummy;
while(index>0)
{
cur=cur.next;
index--;
}
newNode.next=cur.next;
cur.next=newNode;
size++;
}
public void deleteAtIndex(int index) {
if(index>size||index<0)
return;
//要删除就要找到节点前面的位置
ListNode cur = dummy;
while(index>0)
{
cur=cur.next;
index--;
}
cur.next=cur.next.next;
size--;
}
}
/**
* 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);
*/
206 反转链表
双指针法:判断条件为cur是不是null
class Solution {
//双指针
public ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode temp = null;
ListNode cur = head;
while(cur!=null)
{ //tcpc
temp=cur.next;
cur.next=pre;
pre=cur;
cur=temp;
}
return pre;
}
}
递归法
根据双指针法改写
专门设计一个函数reverse(cur,pre)
(双指针里的一层循环在递归里就是进入下一层指针)
注意return
class Solution {
public ListNode reverseList(ListNode head) {
return reverse(head,null); //不要忘记return
}
public ListNode reverse(ListNode cur,ListNode pre)
{
if(cur==null) {return pre;}
ListNode temp = cur.next; //先保存下一个节点
cur.next=pre; //反转
return reverse(temp,cur); //更新 reverse(ListNode cur,ListNode pre)中cur和pre的值,向后移动,之后开启新一轮循环迭代
//不要忘记return
}
}