emmmmmmmmmmmmmmmmmm,链表操作好烦呀,说白了,其实是指针烦。其实我还是未能很理解,指针谁指谁,只能多撸几次代码来增加理解。
#include <stdio.h>
#include <stdlib.h>
typedef int ElementType;
typedef struct _node{
ElementType data;
struct _node *next;
} node;
/**< 其实还是未能很好理解再创建一个list结构,老师说是为了日后可以加入node *tail等操作而准备的;
我现在暂时未能看出门道,只能依葫芦画瓢 */
typedef struct _list
{
node *head;
}list;
void addList(list *plist, ElementType x);
void displayList(list *plist);
int lengthOfList(list *plist);
node *findKth(list *plist, int k);
int findData(list *plist, ElementType x);
void insertData(list *plist, ElementType x, int i);
void deleteData(list *plist, int i);
int lengthOfList(list *plist)
{
node *tmp = plist->head;
int cnt = 0;
while(tmp) /**< 这里的判断条件千万不要用tmp->next,因为最后一个元素next为空,cnt不加一 */
{
cnt++;
tmp = tmp->next;
}
return cnt;
}
void displayList(list *plist)
{
node *tmp = plist->head;
while(tmp)
{
printf("%d ", tmp->data);
tmp = tmp->next;
}
printf("\n");
}
node *findKth(list *plist, int k)
{
node *tmp = plist->head;
int i = 1;
while(tmp!=NULL && i<k)
{
tmp = tmp->next;
i++;
}
if( i==k )
{
return tmp;
}
else
{
printf("finding %d failed\n", k);
return NULL;
}
}
int findData(list *plist, ElementType x)
{
int cnt = 0;
node *tmp = plist->head;
while(tmp)
{
cnt++;
if( tmp->data==x )
return cnt;
tmp = tmp->next;
}
return -1;
}
void addList(list *plist, ElementType x)
{
node *tmp = (node*)malloc(sizeof(node));
tmp->data = x;
tmp->next = NULL;
node *last = plist->head;
if(last) /**< 如果last不为空(为空则代表plist->head为空,即为空链表) */
{
while(last->next)
{
last = last->next;
}
last->next = tmp;
}
else
{
plist->head = tmp;
}
}
void insertData(list *plist, ElementType x, int i)
{
node *tmp;
node *s;
if( i==1 )
{
s = (node*)malloc(sizeof(node));
s->data = x;
s->next = plist->head;
plist->head = s;
}
else
{
tmp = findKth(plist, i-1);
if(tmp==NULL)
{
printf("invalid position\n");
}
else
{
s = (node*)malloc(sizeof(node));
s->data = x;
s->next = tmp->next;
tmp->next = s;
}
}
}
void deleteData(list *plist, int i)
{
node *tmp;
node *s;
if(i==1)
{
tmp = plist->head;
plist->head = tmp->next;
free(tmp);
}
else
{
tmp = findKth(plist, i-1);
if(s==NULL)
{
printf("invalid position\n");
}
else
{
s = tmp->next;
tmp->next = s->next;
free(s);
}
}
}
int main()
{
list phead;
node *pub;
phead.head = NULL;
int n;
scanf("%d", &n);
while( n!=-1 )
{
addList(&phead, n);
scanf("%d", &n);
}
displayList(&phead);
printf("\nLength of the list: %d\n", lengthOfList(&phead));
pub = findKth( &phead, 2);
printf("2nd data: %d\n", pub->data);
printf("data 3 is in position: %d\n", findData(&phead, 3));
insertData(&phead, 10, 1);
displayList(&phead);
printf("delete test3\n");
deleteData(&phead, 3);
displayList(&phead);
printf("delete test1\n");
deleteData(&phead, 1);
displayList(&phead);
system("pause");
}