链表创建、逆置、删除详解
生活随笔
收集整理的這篇文章主要介紹了
链表创建、逆置、删除详解
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
***************************************************
更多精彩,歡迎進入:http://shop115376623.taobao.com
***************************************************
對鏈表的理解:http://www.nowamagic.net/librarys/veda/detail/2220
#include <stdio.h>
//結構體,用整數作數據 ?
//定義節點
typedef struct tNODE{
??? int data;
??? struct tNODE *next;
}NODE;
//刪除 鏈表 ,回收空間
void clear(NODE *head)
{
??? NODE *p;
??? while(head)
??? {
??? ??? p=head->next;//保存下一個結點的地址
??? ??? free(head);//刪除最先的一個結點
??? ??? head=p;//指向下一個結點
??? }
}
//輸出整個 鏈表 中的數據
void write(NODE *head)
{
??? NODE *p;
??? p=head->next;//因為使用帶 頭結點 的 鏈表 ,所以要跳過第一個結點
??? while(p)
??? {
??? ??? printf("%d ", p->data);
??? ??? p=p->next;//后移
??? }
??? printf("\n");
}
// 鏈表 逆序
void reverse(NODE *head)
{
??? NODE *p, *q, *r;
??? if(head->next)//至少有一個數據
??? {
??? ??? p=head->next;//p指向第一個數據結點
??? ??? q=p->next;//q指向第二個結點
??? ??? p->next=NULL;//第一個結點逆序后當然就是最后一個
??? ??? while(q)
??? ??? {
??? ??? ??? r=q->next;//r指向第三個結點
??? ??? ??? q->next=p;//第二個結點的鏈指針指向第一個
??? ??? ??? p=q;//p指向第二個結點
??? ??? ??? q=r;//q指向第三個結點
??? ??? }
??? ??? head->next=p;//讓始終沒理的 頭結點 連到最后一個結點上
??? }
}
//生成 鏈表 ,以-1表示結束
NODE *create()
{
??? NODE *h, *t;
??? int x;
??? h=malloc(sizeof(NODE));//建立 頭結點
??? t=h;
??? scanf("%d", &x);
??? while(x!=-1)
??? {
??? ??? t->next=malloc(sizeof(NODE));
??? ??? t=t->next;
??? ??? t->data=x;
??? ??? scanf("%d", &x);
??? }
??? t->next=NULL;
??? return h;
}
int main()
{
??? NODE *head;
??? head=create();
??? write(head);
??? reverse(head);
??? write(head);
??? clear(head);
??? return 0;
}
總結
以上是生活随笔為你收集整理的链表创建、逆置、删除详解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: List转Json数组
- 下一篇: U8安装包下载地址