title: How can I get access to the current and previous item in a linked list?
body: <p>I'm writing a map generator in Rust which will split the world into sections and then within those sections create rooms in order to connect these rooms. What I would normally do is have a list and then as I iterate through the list get the parent (if there is one) and then run some code to connect these rooms.</p>
  
  <p>I'm struggling with the traversing through a list and getting the parent.</p>
  
  <p>Here are the data structures I currently have:</p>
  
  <pre class="lang-rust prettyprint-override"><code>struct MapSectionPosition {
      x: f32,
      y: f32,
  }
  
  struct MapSectionRect {
      top_left: MapSectionPosition,
      top_right: MapSectionPosition,
      bottom_right: MapSectionPosition,
      bottom_left: MapSectionPosition,
  }
  
  struct MapSection {
      width: f32,
      height: f32,
      points: MapSectionRect,
  }
  
  struct RoomExit {
      position: MapSectionPosition,
  }
  
  struct Room {
      width: f32,
      height: f32,
      exit: RoomExit,
  }
  </code></pre>
  
  <p>At the moment I'm using a linked list:</p>
  
  <pre class="lang-rust prettyprint-override"><code>let mut rooms: LinkedList&lt;Room&gt; = LinkedList::new();
  
  let room = Room {
      width: section.width / 4.0,
      height: section.height / 4.0,
      exit: RoomExit {
          position: MapSectionPosition { x: 20.0, y: 20.0 },
      },
  };
  
  rooms.push_back(room);
  </code></pre>
  
  <p>I'm struggling to both iterate and get the parent, so I'm thinking this might not be the right data structure.</p>
  
  <p>With some playing around I've found a hacky solution. Hopefully this will better illustrate what I'm trying to do and if there is something more elegant.</p>
  
  <pre><code>let mut previous_room: Option&lt;&amp;Room&gt; = None;
  for room in rooms.iter() {
      match previous_room {
          Some(p_room) =&gt; {
              println!("previous {}", p_room.width);
              println!("current {}", room.width);
              println!("connected");
          },
          None =&gt; {
              println!("no previous room");
          }
      }
  
      previous_room = Some(room);
  }
  </code></pre>
  
  <p><strong>Something a little more elegant</strong></p>
  
  <p>If rooms are a slice, then we can use the <code>windows</code> method to create an iterator to access the data in question.</p>
  
  <pre><code>let mut iter = rooms[..].windows(2);
  while let Some([prev, next]) = iter.next() {
      println!("prev - {}", prev.width);
      println!("next - {}", next.width);
      println!("done...")
  }
  </code></pre>
  
  <p>This has been answered before in <a href="https://stackoverflow.com/q/42134874/155423">Are there equivalents to slice::chunks/windows for iterators to loop over pairs, triplets etc?</a></p>