左程云基础班——单链表

本文主要介绍了单链表的相关操作,包括反转链表、查找链表公共部分、判断回文结构、按值划分链表、复制带有随机指针的链表以及解决两个链表相交的问题。通过实例解析,深入理解链表数据结构。
摘要由CSDN通过智能技术生成

左程云基础班——单链表(带头结点)

链表结点

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

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

题目一:反转单向链表

	//头插法
	public static Node ReverseList(Node head) {
   
        Node pre = head.next;
        head.next = null;//头结点置空
        Node next = null;       
        while (pre != null) {
   
            next = pre.next;
            pre.next = head.next;
            head.next = pre;
            pre = next;
        }
        return head;
    }

题目二:打印两个链表的公共部分

	public static void printCommon(Node head1, Node head2) {
   
        Node p = head1.next;
        Node q = head2.next;
        Node com = new Node(-1);
        com.next = null;
        while (p != null && q != null) {
   
            if (p.value < q.value)
                p = p.next;
            else if (p.value > q.value)
                q = q.next;
            else {
   
                System.out.print(p.value + " ");
                p = p.next;
                q = q.next;
            }
        }
    }

题目三:判断一个链表是否为回文结构

	public static boolean isPalindromList(Node head) {
   
        Node cur = head.next;
        //栈逆序输出链表
        Stack<Node> stack = new Stack<>();
        while (cur != null) {
   
            stack.push(cur);
            cur = cur.next;
        }
        cur = head.next;
        while (cur != null) {
   
            if (cur.value != stack.pop().value)
                return false;
            cur = cur.next;
        }
        return true;
    }

题目四:将单向链表按某值划分成左边小、中间相等、右边大的形式

方法一:用三个链表分别保存,再合并

	//方法一:用三个链表分别保存,再合并
	public static Node SmallerEqualBigger_1(Node head, int pivot) {
   
        if (head.next == null) {
   
            return head;
        }
        //小数的链表
        Node small_head = new Node(-1);
        small_head.next = null;
        Node small_tail = small_head;
		//相等数的链表
        Node equal_head = new Node(-1);
        equal_head.next = null;
        Node equal_tail = equal_head;
		//大数的链表
        Node big_head = new Node(-1);
        big_head.next = null;
        Node big_tail = big_head;
		//保存结果的链表
        Node res = head;
        head = head.next;//用head指针遍历
        res.next 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值