首页 > 编程语言 > 详细

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

时间:2018-09-21 17:23:36      阅读:261      评论:0      收藏:0      [点我收藏+]

#链表
链表是面试时被提及最频繁的数据结构。链表就是通过指针将一个个节点连接起来。链表是非连续的动态内存空间,链表的查找比数组慢,但是添加和删除比数组快。
###链表声明
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》 —何海涛

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

原文:https://www.cnblogs.com/hiyoung/p/9687502.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!