# 数据结构与算法-链表

1 public class ListNode {
2     int val;
3     ListNode next;
4     public ListNode(int val) {
5         this.val = val;
6         this.next = null;
7     }
8 }            

 1 public void insertList(ListNode head, int val) {
2     ListNode tempNode = new ListNode(val);
3     if (head == null) {
5     }else {
7         while (p.next != null) {
8             p = p.next;
9         }
10         p.next = tempNode;
11     }
12 }    

 1 public void deleteListNode(ListNode head, int val) {
3     if (head.val == val) {//头节点为要删除节点
5     } else {
7         //删除节点需要知道前一个节点，所以判断p.next.val是不是和目标相等
8         while (p.next !=null && p.next.val != val) {
9             p = p.next;
10         }
11         if (p.next !=null) {
12             p.next = p.next.next;//删除节点
13         }
14     }
15 }

 1 public void printList1(ListNode head) {
2     if (head == null) return;
3     Stack<ListNode> stack = new Stack<ListNode>();
5     while (p != null) {
6         stack.push(p);
7         p = p.next;
8     }
9     while (!stack.isEmpty()) {
10         p = stack.pop();
11         System.out.print(p.val+" ");
12     }
13 }

1 public void printList2 (ListNode head) {
2     if (head != null) {
3         if (head.next != null) {
5         }
7     }
8 }

 1 public ListNode reverseList (ListNode head) {
2     ListNode pre = null;
3     ListNode next;
4     while (head != null) {
9     }
10     return pre;
11 }

 1 public class DoubleNode {
2     public int val;
3     public DoubleNode pre;
4     public DoubleNode next;
5     public DoubleNode (int val){
6         this.val=val;
7     }
8 }
10     DoubleNode pre=null;
11     DoubleNode next=null;
13         //反转第一个节点
19     }
20     return pre;//返回新头节点
21 }

《程序员代码面试指南：IT名企算法与数据结构题目最优解》—左程云
《剑指Offer》 —何海涛

posted @ 2018-09-21 17:10 hiyoung 阅读(...) 评论(...) 编辑 收藏