You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: Linked List/README.markdown
+13Lines changed: 13 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -471,6 +471,7 @@ This will print the list like so:
471
471
472
472
How about reversing a list, so that the head becomes the tail and vice versa? There is a very fast algorithm for that:
473
473
474
+
Iterative Approach:
474
475
```swift
475
476
publicfuncreverse() {
476
477
var node = head
@@ -482,6 +483,18 @@ How about reversing a list, so that the head becomes the tail and vice versa? Th
482
483
}
483
484
}
484
485
```
486
+
Recursive Approach:
487
+
```swift
488
+
publicfuncreverse(node: head) {
489
+
if!head ||!head.next {
490
+
return head
491
+
}
492
+
let temp =reverse(head.next)
493
+
head.next.next= head
494
+
head.next=nil
495
+
return temp
496
+
}
497
+
```
485
498
486
499
This loops through the entire list and simply swaps the `next` and `previous` pointers of each node. It also moves the `head` pointer to the very last element. (If you had a tail pointer you'd also need to update it.) You end up with something like this:
0 commit comments