Thread: Delete olnly the last node

  1. #1
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694

    Delete olnly the last node

    <<< split from Deleting nodes from a linked list >>>
    Hello.I am new in C.I must write code for the game reversi(or othello).I have problem with the command UNDO.I want to delete only the last node of a simply linked list.I thought that what i must do is to go the prelast node,put there next=NULL; and then free the last node.However i have not managed to navigate through the list,because i get segmentation fault.
    Thanks in advance
    //This is my first post in this forum

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Consider something like
    Code:
    while ( curr->next != NULL ) {
      prev = curr;
      curr = curr->next;
    }
    curr will be the last node
    prev will be the node (next to last) pointing to it.

    The only trick is when you're deleting the only node in the list.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    Quote Originally Posted by Salem View Post
    Consider something like
    Code:
    while ( curr->next != NULL ) {
      prev = curr;
      curr = curr->next;
    }
    curr will be the last node
    prev will be the node (next to last) pointing to it.

    The only trick is when you're deleting the only node in the list.
    ok.thanks.By the way i found another way to do it.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help Debugging my AVL tree program.
    By Nextstopearth in forum C Programming
    Replies: 2
    Last Post: 04-04-2009, 01:48 AM
  2. Unknown memory leak with linked lists...
    By RaDeuX in forum C Programming
    Replies: 6
    Last Post: 12-07-2008, 04:09 AM
  3. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  4. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 10:33 AM
  5. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of Cprogramming.com
    Replies: 18
    Last Post: 06-18-2002, 01:27 PM