-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyLinkedList.java
More file actions
105 lines (93 loc) · 1.93 KB
/
MyLinkedList.java
File metadata and controls
105 lines (93 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
class LinkedListNode
{
int val;
LinkedListNode next;
LinkedListNode()
{
}
LinkedListNode(int val)
{
this.val = val;
}
}
class MyLinkedList
{
int size;//链表元素的个数
LinkedListNode head;//虚拟头节点
public MyLinkedList()
{
size = 0;
head = new LinkedListNode(0);
}
public int get(int index)
{
if (index < 0 || index >= size)
return -1;
LinkedListNode cur = head;
for (int i = 0; i <= index; i++)
{
cur = cur.next;
}
return cur.val;
}
public void addAtHead(int val)
{
addAtIndex(0, val);
}
public void addAtTail(int val)
{
addAtIndex(size, val);
}
public void addAtIndex(int index, int val)
{
if (index > size)
return;
if (index < 0)
{
index = 0;
}
size++;
LinkedListNode li = new LinkedListNode(val);
LinkedListNode cur = head;
for (int i = 0; i < index; i++)
{
cur = cur.next;
}
li.next = cur.next;
cur.next = li;
}
public void deleteAtIndex(int index)
{
if (index < 0 || index >= size)
return;
size--;
if (index == 0)
{
head = head.next;
}
LinkedListNode cur = head;
for (int i = 0; i < index; i++)
{
cur = cur.next;
}
cur.next = cur.next.next;
}
public void print()
{
LinkedListNode cur = head;
for (int i = 0; i < size; i++)
{
cur = cur.next;
System.out.println(cur.val);
}
}
public static void main(String[] args)
{
MyLinkedList ml = new MyLinkedList();
ml.addAtHead(1);
ml.addAtTail(2);
ml.addAtHead(3);
ml.addAtIndex(1, 4);
ml.print();
}
}