链表设计

单链表:单指向链表

双向链表:前后都指向链表

题目1:单链表和双向链表如何反转

package day2;
//反转链表
public class Code01_ReverseList {
	
	public static class Node {
		public int value;
		public Node next;
		public Node(int value,Node next) {
			this.value = value;
			this.next = next;
		}
	}
	
	public static class DoubleNode {
		public int value;
		public DoubleNode last;
		public DoubleNode next;
		
		public DoubleNode(int data) {
			value = data;
		}
	}
	
//	反转单链表
	public static Node reverseLinkedList(Node head) {
		/*
		 *准备一个之前的变量
		 *在准备一个后来的变量
		 *
		 */
		Node pre = null;
		Node next = null;
		while(head != null) {
			next = head.next;
			head.next = pre;
			pre = head;
			head = next;	
		}
		return pre;
	}
	
//	反转双向链表
	public static DoubleNode reverseDoubleList(DoubleNode head) {
		DoubleNode pre = null;
		DoubleNode next = null;
		while(head != null) {
			next = head.next;
			head.next = pre;
			head.next = next;
			pre = head;
			head = next;
		}
		return pre;	
	}
	
}

题目2:把给定值都删除

package day2;
//删除链表中的一个元素
import day2.Code01_ReverseList.Node;

public class Code02_DeleteGivenValue {
	public static class Node {
		public int value;
		public Node next;
		public Node(int value,Node next) {
			this.value = value;
			this.next = next;
		}
	}
	public static Node removeValue(Node head,int num) {
		while(head != null) {
			if(head.value != num) {
				break;
			}
			head = head.next;
		}
		//head来到第一个不需要删的位置
		Node pre = head;
		Node cur = head;
		//
		while(cur != null) {
			if(cur.value == num) {
				pre.next = cur.next;	
			} else {
				pre = cur;
			}
			cur = cur.next;
		}	
		return head;
	}
}	
posted @ 2021-06-28 19:54  IT小五  阅读(63)  评论(0)    收藏  举报