链表插入算法

最近再看swish-e的源代码的时候,觉得里面的一种链表插入(新节点插入到末尾)的算法不错。
基本的算法中需要遍历一下(当然也可以增加一个tail节点指针)。我整理了一下,写了一个测试程序。
#include <stdio.h>
#include <unistd.h>
void
insertlist(struct conlist **list, char *line);
typedef union
{
struct conlist *listp;
char *data;
} otherlist;
struct conlist
{
char line[1];
struct conlist *next;
otherlist other_list;
};
int
main(int argc, char *argv[]) {
int opt;
struct conlist *list = NULL;
while((opt = getopt(argc, argv, "c:")) != -1) {
switch(opt) {
case 'c':{
while(*optarg) {
printf("the option is:%s/n",optarg);
optarg++;
}
}
break;
}
}
for(; optind < argc; optind++) {

//printf("argument: %s/n", argv[optind]);
insertlist(&list,argv[optind]);
}
struct conlist *startlist;
startlist = list;
if (startlist == NULL) {
printf(" list error/n");
}
while(startlist) {
printf("the content is: %s/n", startlist->line);
startlist = startlist->next;
}
return 0;
}
void
insertlist(struct conlist **listnode, char *line) {
struct conlist *plist, *newnode;
plist = *listnode;
newnode = (struct conlist *)malloc(sizeof(struct conlist) + strlen(line));
if (newnode == NULL) {
printf("malloc error/n");
}
newnode->next = NULL;
memcpy(newnode->line, line, strlen(line)+1);
printf("the string is %s:/n", newnode->line);
if (*listnode == NULL) {
*listnode = newnode;
printf("NULL /n");
}
else
{
printf("insert another/n");
plist->other_list.listp->next = newnode;
}
(*listnode)->other_list.listp = newnode;
//struct conlist *startlist;
//startlist = plist;
//while(startlist) {
// printf("the content is: %s/n", startlist->line);
// startlist = startlist->next;
//}
}


就是通过两个指针进行链表的插入,otherlist.listp也指向tail节点。

你可能感兴趣的:(算法,struct,list,String,null,insert)