> For the complete documentation index, see [llms.txt](https://docs.ramsdenj.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.ramsdenj.com/introduction-4/notes/linked_lists.md).

# Linked Lists

## Slow and Fast Pointers

Can be used to find the middle or a cycle. If a cycle occurs the fast pointer will eventually meet the slow.

Find middle:

```python
class Node:
    def __init__(self, val):
        self.val = val
        self.next = None

    def __str__(self):
        return str(self.val)

print("Creating even linked list (length 4)")
# [1, 2, 3, 4]
head = Node(1)
n = head
for i in range(2, 5):
    n.next = Node(i)
    n = n.next

n = head
while n:
    print(n.val)
    n = n.next

fast = head
slow = head
while fast and fast.next:
    fast = fast.next.next
    slow = slow.next

print("Middle: ", slow.val)

print("Creating odd linked list (length 5)")
# [1, 2, 3, 4, 5]
head = Node(1)
n = head
for i in range(2, 6):
    n.next = Node(i)
    n = n.next

n = head
while n:
    print(n.val)
    n = n.next

fast = head
slow = head
while fast and fast.next:
    fast = fast.next.next
    slow = slow.next

print("Middle: ", slow.val)
```

## Reversal

```python
# Reverse
n = head
prev = None
while n:
    # Create temp for next
    nextemp = n.next
    # Set next to prev
    n.next = prev
    # Update prev
    prev = n
    # Go to next node
    n = nextemp

print("\nReversed linked list:")
# Last ends up as prev
n = prev
while n:
    print(n.val)
    n = n.next
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.ramsdenj.com/introduction-4/notes/linked_lists.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
