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