您的位置:首页 > 其它

单向链表操作总结

2016-10-27 22:17 393 查看
1.链表的建立:

struct Listnode
{
Datatype data;
struct Listnode *next;
};


顺序链表:

head指向第一个创造pre的新空间

rear不断更新,作为前一个pre空间的地址

pre不断创造新空间

struct ListNode *pre,*rear,*head;
head = rear = (ListNode *)malloc(sizeof(struct ListNode));
head = NULL;
while(1)
{
pre = (ListNode *)malloc(sizeof(struct ListNode));
pre->next = NULL;
int x ;
scanf("%d",&x);
if(x != -1)
pre->data = x;
else
break;
if(head == NULL)
head = pre;
else
rear->next = pre;
rear = pre;
}
return head;


逆序链表:

pre创造新空间指向head

head更新为新空间pre的地址

struct ListNode *pre,*head;
head = NULL;
while(1)
{
int a;
scanf("%d",&a);
if(a == -1)
break;
pre = (ListNode *)malloc(sizeof(struct ListNode));
pre->data = a;
pre->next = head;
head = pre;
}
return head;


2.遍历单向链表

struct ListNode *temp;
for(temp = head; temp != NULL; temp=temp->next)
...


3.链表的插入

结点t 插在结点p 之后:

t->next = p->next;

p->next = t;

结点t 插在结点表头:

t->next = head;

head = t ;

扩展: 非二分的插入排序

//list2 插入 list1
struct ListNode *mergelists(struct ListNode *list1, struct ListNode *list2)
{
struct ListNode *temp,*temp2,*now;
for(temp = list2; temp != NULL; temp=temp->next)
{
now = (struct ListNode *)malloc(sizeof(struct ListNode));
now->data = temp->data;
if(now->data < list1->data)
{
now->next = list1;
list1 = now;
continue;
}
for(temp2 = list1; temp2->next != NULL; temp2=temp2->next)
{
if(now->data < temp2->next->data)
{
now->next = temp2->next;
temp2->next = now;
break;
}
}
if(temp2->next == NULL)
{
now->next = NULL;
temp2->next = now;
}
}
return list1;
}


4.链表的删除

删除p后面的结点

t = p->next;

p->next = t->next;

free(t);

5.链表的冒泡排序

struct ListNode* sortlink(struct ListNode *head)
{
struct ListNode *endpt;
struct ListNode *p;
struct ListNode *p1,*p2;
p1 = (struct ListNode *) malloc(sizeof(struct ListNode));
p1->next = head;    //注意理解:我们增加一个节点,放在第一个节点的前面,主要是为了便于比较。因为第一个节点没有前驱,我们不能交换地址
head = p1;
for(endpt = NULL; endpt != head; endpt = p)
{
for (p = p1 = head; p1->next->next != endpt; p1 = p1->next)
{
if (p1->next->data > p1->next->next->data)    //如果前面的节点键值比后面节点的键值大,则交换
{
p2 = p1->next->next;
p1->next->next = p2->next;
p2->next = p1->next;
p1->next = p2;
p = p1->next->next;
}
}
}
p1 = head;
head = head->next;      //让head指向排序后的第一个节点
free (p1);              //释放p1
p1 = NULL;              //p1置为NULL,保证不产生“野指针”,即地址不确定的指针变量
return head;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: