左程云著算法与数据结构题目最优解笔记-链表

链表

链表是面试时被提及最频繁的数据结构。链表就是通过指针将一个个节点连接起来。链表是非连续的动态内存空间,链表的查找比数组慢,但是添加和删除比数组快。

链表声明

public class ListNode {
    int val;
    ListNode next;
    public ListNode(int val) {
        this.val = val;
        this.next = null;
    }
}

链表的添加

public void insertList(ListNode head, int val) {
    ListNode tempNode = new ListNode(val);
    if (head == null) {
        head = tempNode;
    }else {
        ListNode p = head;
        while (p.next != null) {
            p = p.next;
        }
        p.next = tempNode;
    }
}

链表的删除

public void deleteListNode(ListNode head, int val) {
    if (head ==null) return;//为了鲁棒性
    if (head.val == val) {//头节点为要删除节点
        head = head.next;
    } else {
        ListNode p = head;
        //删除节点需要知道前一个节点,所以判断p.next.val是不是和目标相等
        while (p.next !=null && p.next.val != val) {
            p = p.next;
        }
        if (p.next !=null) {
            p.next = p.next.next;//删除节点
        }
    }
}

从尾到头打印链表

方法1:使用栈结构

public void printList1(ListNode head) {
    if (head == null) return;
    Stack<ListNode> stack = new Stack<ListNode>();
    ListNode p = head;
    while (p != null) {
        stack.push(p);
        p = p.next;
    }
    while (!stack.isEmpty()) {
        p = stack.pop();
        System.out.print(p.val+" ");
    }
}

方法2:递归

public void printList2 (ListNode head) {
    if (head != null) {
        if (head.next != null) {
            printList2(head.next);
        }
        System.out.print(head.val+" ");
    }
}

注:递归的过程相当于栈。

反转单链表

public ListNode reverseList (ListNode head) {
    ListNode pre = null;
    ListNode next;
    while (head != null) {
        next = head.next;
        head.next = pre;
        pre = head;
        head = next;
    }
    return pre;
}

学习数据结构与算法的记录和整理,如有错误或意见请帮忙指出,以后会持续更新。。。。
参考书籍:
《程序员代码面试指南:IT名企算法与数据结构题目最优解》—左程云
《剑指Offer》 —何海涛

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值