单向链表
public class Node {
public int value;
public Node next;
public Node(int data) {
value = data;
}
}
双向链表
public class DoubleNode {
public int value;
public Node next;
public Node pre;
public Node(int data) {
value = data;
}
}
第一题
问题描述:单链表反转
实例:a -> b -> c c -> b -> a
package com.lzf2.class02;
/**
* 单链表反转
*/
public class LinkedInReversal {
public static class Node{
int value;
Node next;
public Node(Node next) {
this.next = next;
}
}
public static Node reversal(Node head){
Node pree = null;
Node curr = head;
while (curr != null){
Node next = curr.next;
curr.next = pree;
pree = curr;
curr = next;
}
return pree;
}
}
第二题
问题描述:在链表中把给定值的结点都删除
实例:a->a->b->c->a 指定值a b->C
public class LinkedDeleteAll {
public static class Node{
int value;
Node next;
public Node(Node next) {
this.next = next;
}
}
public static Node delete(Node head,int val){
while (head != null && head.value == val){
head = head.next;
}
//head可能为null
Node curr = head;
Node pree = head;
while (curr != null){
if(curr.value == val){
pree.next = curr.next;
}else {
pree = curr;
}
curr = curr.next;
}
return head;
}
}