目录
了解链表
-
链表适合插入,删除操作;
-
链表存储数据的内存空间是不连续的;
-
链表有单链表[只有后继节点],双链表[前驱节点和后继节点],循环链表.
链表的定义 Java版本
class ListNode{ int val; ListNode next; public ListNode() { } public ListNode(int val, ListNode next) { this.val = val; this.next = next; } public ListNode(int val) { this.val = val; } }
203.移除链表元素
之前上课讲过,每次都是看懂了,写就不会了.总是逻辑不够清晰,或者考虑情况不全面.
正解:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode removeElements(ListNode head, int val) { if(head==null) {return head;} // 因为删除可能涉及到头节点,所以设置dummy节点,统一操作 ListNode dummy = new ListNode(-1, head); ListNode pre = dummy; ListNode cur = head; while (cur != null) { if (cur.val == val) { pre.next = cur.next; } else { pre = cur; } cur = cur.next; } return dummy.next; // while(head!=null && head.val==val){ // head = head.next; } // //第一个while循环,删除当前满足条件的节点值 // ListNode curr = head; // //第二个while循环,删除满足条件的下一个节点值 // while(curr!=null){ // while(curr.next!=null && curr.next.val == val){ // curr.next = curr.next.next; // } // curr = curr.next; // } // return head; } }
206.翻转链表
之前写过,久了还是忘了,自己没有充分理解,现在看到这个代码,temp=cur.next;这个我理解错了,就一直在想,怎么一开始反转的时候就把第二个值与null连接起来了, 后知后觉, 才发现是我搞错了cur.next是存放的下一个节点的地址,不是值.
正解[双指针]:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode reverseList(ListNode head) { ListNode pre=null,cur=head; ListNode temp; while(cur!=null){ temp=cur.next; cur.next=pre; pre=cur; cur=temp; } return pre; } }
正解[正向递归]:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode reverseList(ListNode head) { return reverseFunction(null,head) } //这个函数实现翻转操作 public ListNode reverseFunction(ListNode pre,ListNode cur){ if(cur==null){return pre}; //这里的返回值不应该直接写个null,这样考虑不全面,写pre做到了两种情况:1,head是空链表;2,指针走到链表末尾了,可以结束了. ListNode tmp; tmp=cur.next;//利用tmp作为翻转函数的参数,实现下次翻转 cur.next=pre; return reverseFunction(cur,tmp); } }
没做设计链表这道题,原因:懒.代码好长.