vault backup: 2024-03-21 22:58:58
This commit is contained in:
35
Semester 2/Programming 2/Week 10 Revision/Q4.md
Normal file
35
Semester 2/Programming 2/Week 10 Revision/Q4.md
Normal file
@@ -0,0 +1,35 @@
|
||||
```java
|
||||
public class IntNode
|
||||
{
|
||||
public int info;
|
||||
public IntNode next;
|
||||
}
|
||||
```
|
||||

|
||||
a) Write code to add 50 to the appropriate field of the node pointed to by temp.
|
||||
|
||||
```java
|
||||
temp.info += 50;
|
||||
```
|
||||
|
||||
b) Write code to remove from the list the item after temp.
|
||||
```java
|
||||
temp.next = temp.next.next;
|
||||
```
|
||||
|
||||
c) Write the code to remove from the list temp.
|
||||
```java
|
||||
temp.info = temp.next.info; // Assign the next node's value to temp - this will overwrite temp's value.
|
||||
temp.next = temp.next.next; // Set the pointer for temp's next node to the node after the value taken for temp - this effectively clones temp.next and replaces temp.
|
||||
```
|
||||
|
||||
d) Write code to go through the list and to sum all the values within the list. You may assume the existence of head, a reference to the start of the list.
|
||||
|
||||
```java
|
||||
IntNode current = head;
|
||||
int sum = 0;
|
||||
while ( current != null ) {
|
||||
sum += current.info;
|
||||
current = current.next;
|
||||
}
|
||||
```
|
||||
Reference in New Issue
Block a user