天天看點

單連結清單未完成

#include <stdio.h>

#include <stdlib.h>

typedef char TYPE;

typedef struct Node

{

 TYPE value;

 struct Node * next;

}ListNode;

ListNode * creatList(const TYPE *data);

ListNode * insertList(const ListNode * head, const TYPE data, const int pos);

int main()

{

 TYPE *data = "abc";

 ListNode * listHead;

 listHead = creatList(data);

 printf("%c\n",listHead->value);

 listHead = insertList(listHead, 'e', 2);

 printf("%c\n",listHead->next->value);

 return 0;

}

//單連結清單的建立

ListNode * creatList(const TYPE *data)

{

 ListNode * pList = NULL;

 ListNode * head = NULL;

 int len = strlen(data);

 if((ListNode *)malloc(sizeof(TYPE)+4))

 {

  pList = (ListNode *)malloc(sizeof(TYPE)+4);

  head = pList;

  int i = 0;

  for(;i<len-1;i++)

  {

   pList->value = data[i];

   if((ListNode *)malloc(sizeof(TYPE)+4))

   {

    pList->next = (ListNode *)malloc(sizeof(TYPE)+4);

    pList = pList->next;

   }

  }

  pList->value = data[i];

  pList->next = NULL;

 }

 return head;

}

//單連結清單插入,若pos大于連結清單長度則插在連結清單尾部。

ListNode * insertList(const ListNode * head, const TYPE data, const int pos)

{

 ListNode * pList = head;

 ListNode * insert = NULL;

 int len = 0;

 int i = 0;

 insert = (ListNode *)malloc(sizeof(TYPE)+4);

 while(NULL != pList->next)

 {

  len++;

  pList = pList->next;

 }

 if(len<pos)

 {

  pList->next = insert;

  insert->next = NULL;

  insert->value = data;

 }

 else

 {

  pList = head;

  if(pos == 1)

  {

   insert->next = pList;

   head = insert;

   insert->value = data;

  }

  else

  {

   for(;i<pos-2;i++)

   {

    pList = pList->next;

   }

   insert->next = pList->next;

   pList->next = insert;

   insert->value = data;

  }

 }

 return head;

}