学习目的是删除链表的某个元素,通过循环和递归方式实现。如下
先定义一个node节点
public class Node {
int val;
Node next;
Node(){};
Node(int val){
this.val = val;
}
public Node(int val,Node next){
this.val = val;
this.next = next;
}
public Node (int[] nums) {
if (nums==null || nums.length==0) {
throw new IllegalArgumentException("数组不合法");
}
val = nums[0];
Node cur = this;
for (int i=1;i<nums.length;i++){
cur.next = new Node(nums[i]);
cur = cur.next;
}
}
@Override
public String toString () {
StringBuilder stringBuilder = new StringBuilder();
Node cur = this;
while (cur!=null){
stringBuilder.append(cur.val+"->");
cur = cur.next;
}
stringBuilder.append("null");
return stringBuilder.toString();
}
}
public class CircleLinkList {
public static void main (String[] args) {
int[] nums = {1,2,3,6,4,5,6};
Node head = new Node(nums);
System.out.println(head);
Node listNode = removeElements1(head,3);
System.out.println(listNode);
}
public static Node removeElements(Node head, int val) {
while (head!=null&&head.val == val){
Node delNode = head;
head = head.next;
delNode.next = null;
}
if (head == null) {
return head;
}
Node pre = head;
while (pre.next != null){
if (pre.next.val == val) {
Node delNode = pre.next;
pre.next = delNode.next;
delNode.next = null;
}else{
pre = pre.next;
}
}
return head;
}
public static Node removeElements1(Node head, int val) {
if (head == null){
return head;
}
Node node = removeElements1(head.next , val);
if (head.val == val){
return node;
}else{
head.next = node;
return head;
}
}
}
上面就是递归和循环删除链表的方法,我们发现递归移除链表太perfect!
|