还是转java了 用java刷题的感觉就是非常的轻松愉快 只能说java火不是没有道理的
- class MyLinkedList {
- LinkedList prehead;
- class LinkedList{
- int val;
- LinkedList next;
- LinkedList(){
- }
- LinkedList(int val){
- this.val=val;
-
- }
- }
- public MyLinkedList() {
- prehead= new LinkedList();
- }
-
- public int get(int index) {
- LinkedList cur= prehead.next;
- int count=0;
- while(cur !=null){
- if(count==index){
- return cur.val;
- }
- cur=cur.next;
- count++;
- }
- return -1;
- }
-
- public void addAtHead(int val) {
- LinkedList node = new LinkedList(val);
- node.next=prehead.next;
- prehead.next=node;
- }
-
- public void addAtTail(int val) {
- LinkedList cur= prehead;
- LinkedList node = new LinkedList(val);
- while(cur.next!=null){
- cur=cur.next;
- }
- cur.next=node;
- }
-
- public void addAtIndex(int index, int val) {
- LinkedList pre= prehead;
- LinkedList cur=prehead.next;
- LinkedList node = new LinkedList(val);
- int count=0;
- while(cur!=null){
- if(count==index){
- pre.next=node;
- node.next=cur;
- return;
- }
- cur=cur.next;
- pre=pre.next;
- count++;
- }
- if(index==count){
- addAtTail(val);
- }
- }
-
- public void deleteAtIndex(int index) {
- int count=0;
- LinkedList pre= prehead;
- while(pre.next!=null){
- if(count==index){
- pre.next=pre.next.next;
- return;
- }
- pre=pre.next;
- count++;
- }
-
- }
- }
设计链表 用C++写非常困难 但是用java的话就简单太多了 很多细节都不用处理 就是注意下面几个点:1 this.val=val 这是java中的叫隐藏的this调用吧 2 你这个prehead也就是函数中的局部变量 你要是说想全局去显示的话,你需要把它写到属性的位置。
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre=null;
ListNode cur=head;
while(cur!=null){
ListNode tmp= cur.next;
cur.next=pre;
pre=cur;
cur=tmp;
}
return pre;
}
}
这个还是说要想到 不是说一下子操作两个结点 而是一个结点一个结点的操作 且最后是Null 所以不需要新加一个头结点。