• API
• FAQ
• Tools
• Archive
SHARE
TWEET

# Untitled

a guest Sep 16th, 2019 137 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. typedef struct {
2.     int val;
3.     int len;
6.
7. /** Initialize your data structure here. */
8.
15. }
16.
17.
20.     tmp = obj;
21.     /*while(tmp) {
22.         printf("%d ", tmp->val);
23.         tmp = tmp->next;
24.     }*/
25.     for(int i=0; i<obj->len; i++) {
26.         printf("%d ", tmp->val);
27.         tmp = tmp->next;
28.     }
29.     printf("\n");
30. }
31.
32. /** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */
34.     if(index >= obj->len)
35.         return -1;
36.     int i=0;
38.     while(i!=index) {
39.         tmp = tmp->next;
40.         i++;
41.     }
42.     return tmp->val;
43. }
44.
45. /** 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. */
50.     obj->len++;
51.     //obj = obj->next;
53.
54. }
55.
56. /** Append a node of value val to the last element of the linked list. */
58.     if(obj->len == 0) {
60.         return;
61.     }
63.     new->val = val;
64.     new->next = NULL;
66.
67.     while(tmp->next) {
68.         //tmp = tmp->next;
69.         //printf("%d ", tmp->val);
70.         tmp = tmp->next;
71.     }
72.     tmp->next = new;
73.     obj->len++;
74. }
75.
76. /** 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. */
78.     if(index > obj->len || index<0) {
79.         return;
80.     }
81.     else if(index == 0) {
83.         return;
84.     }
86.     new->val = val;
88.     int i=0;
89.     while(i != index-1) {
90.         i++;
91.         tmp = tmp->next;
92.     }
93.     new->next = tmp->next;
94.     tmp->next = new;
95.     obj->len++;
96.
97.     //display(obj);
98. }
99.
100. /** Delete the index-th node in the linked list, if the index is valid. */
104.
105.     if(index >= obj->len || index<0 || obj->len==0) {
106.         return;
107.     }
108.     else if(index == 0) {
109.         obj->val = p2->val;
110.         obj->next = p2->next;
111.         free(p1);
112.     }
113.     else {
114.         int i=0;
115.         while(i != index-1) {
116.             p1 = p1->next;
117.             p2++;
118.         }
119.         p1->val = p2->val;
120.         p1->next = p2->next;
121.         free(p2);
122.     }
123.     obj->len--;
124.     //display(obj);
125. }
126.
129.     while(obj) {
130.         obj = obj->next;
131.         free(curr);
132.         curr = obj;
133.     }
134. }
135.
136.
137. int main()
138. {
141.     display(obj);
143.     display(obj);
144.
146.     display(obj);
148.     display(obj);
150.     display(obj);
152.     display(obj);
154.     display(obj);