Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 2fdd8b8

Browse files
Merge pull request #795 from pragatiahuja/master
final README
2 parents 12a6b93 + 15229cf commit 2fdd8b8

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

‎Linked List/README.markdown

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -471,6 +471,7 @@ This will print the list like so:
471471

472472
How about reversing a list, so that the head becomes the tail and vice versa? There is a very fast algorithm for that:
473473

474+
Iterative Approach:
474475
```swift
475476
public func reverse() {
476477
var node = head
@@ -482,6 +483,18 @@ How about reversing a list, so that the head becomes the tail and vice versa? Th
482483
}
483484
}
484485
```
486+
Recursive Approach:
487+
```swift
488+
public func reverse(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+
```
485498

486499
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:
487500

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /