单向链表与双向链表简单应用

前言

链表相关的问题几乎都是coding问题

1. 单向链表如何反转

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;
	}

2. 双向链表如何反转

public static DoubleNode reverseDoubleList(DoubleNode head) {
    
    
		DoubleNode pre = null;
		DoubleNode next = null;
		while (head != null) {
    
    
			next = head.next;
			head.next = pre;
			head.last = next;
			pre = head;
			head = next;
		}
		return pre;
	}

3. 将链表给定值都删除

public class Code02_DeleteGivenValue {
    
    

	public static class Node {
    
    
		public int value;
		public Node next;

		public Node(int data) {
    
    
			this.value = data;
		}
	}

	// head = removeValue(head, 2);
	public static Node removeValue(Node head, int num) {
    
    
		// head 来到第一个不需要删的位置,防止把链表头指针删掉
		while (head != null) {
    
    
			if (head.value != num) {
    
    
				break;
			}
			head = head.next;
		}

		Node pre = head; //pre  上一个不等于 要删数字 的位置
		Node cur = head; //
		while (cur != null) {
    
    
			if (cur.value == num) {
    
    
				pre.next = cur.next;
			} else {
    
    
				pre = cur;
			}
			cur = cur.next;
		}
		return head;
	}

}

猜你喜欢

转载自blog.csdn.net/ws13575291650/article/details/113694839