题目
- 设计一个单链表,包含next指针、val值,然后设置了一系列函数方法,给出方法的具体实现。
实现
- 基本就是函数实现,无难度。。。。。。类似于队列、栈一类的实现
源代码
class MyLinkedList {
ListNode head;//头指针
ListNode last;//尾指针
int total;//节点总数
class ListNode {
ListNode next;
int val;
public ListNode(int val) {
this.val = val;
this.next = null;
}
}
/** Initialize your data structure here. */
public MyLinkedList() {
//初始化
this.head = null;
this.last = head;
this.total = 0;
}
/** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */
public int get(int index) {
if (index > total-1 || index < 0) return -1;
ListNode temp = head;
for (int i = 0; i < index; i++) {
temp = temp.next;
}
return temp.val;
}
/** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */
public void addAtHead(int val) {
ListNode newHead = new ListNode(val);
newHead.next = head;
if (head == null) last = newHead;
head = newHead;
this.total++;
}
/** Append a node of value val to the last element of the linked list. */
public void addAtTail(int val) {
ListNode newLast = new ListNode(val);
last.next = newLast;
last = newLast;
this.total++;
}
/** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */
public void addAtIndex(int index, int val) {
if (index < 0 || index > total) return;
if (index == 0) {
this.addAtHead(val);
return;
}
if (index == total) {
this.addAtTail(val);
return;
}
ListNode newNode = new ListNode(val);
ListNode pre = head;
for (int i=0; i<index-1; i++) pre = pre.next;
newNode.next = pre.next;
pre.next = newNode;
this.total++;
}
/** Delete the index-th node in the linked list, if the index is valid. */
public void deleteAtIndex(int index) {
if (index < 0 || index >= total || head == null) return;
if (index == 0) {
if (head == last) last = last.next;
head = head.next;
this.total--;
return;
}
ListNode pre = head;
for (int i=0; i<index-1; i++) pre = pre.next;
if (index == total-1) last = pre;
pre.next = pre.next.next;
this.total--;
}
private void traverseList(ListNode head) {
ListNode temp = head;
while (temp != null) {
System.out.println(temp.val);
temp = temp.next;
}
}
}
/**
* Your MyLinkedList object will be instantiated and called as such:
* MyLinkedList obj = new MyLinkedList();
* int param_1 = obj.get(index);
* obj.addAtHead(val);
* obj.addAtTail(val);
* obj.addAtIndex(index,val);
* obj.deleteAtIndex(index);
*/
网友评论