C语言链表逆置

介绍两种单链表逆置的算法,头插法和递归法。
不说废话上代码。

typedef struct LNode{
    int data;
    struct LNode *next;
}LNode, *LinkList;

头插法

LinkList reverse(LinkList head)
{
    LNode* temp = NULL,*Phead = NULL;
    while (head != NULL) {
        temp = head;
        head = head->next;
        temp->next = Phead;
        Phead = temp;
        
    }
    return Phead;
}

现在说明一下头插法的原理

现在开始debug这个函数。
假设现在需要对 1->2->3->4->5->6->7 这个链表进行逆置
函数首先初始化了两个LNode 节点 temp和Phead
接下来就是循环
第一次循环 
1->2->3->4->5->6->7  temp = head  (将head的节点赋值给temp)
   2->3->4->5->6->7  head = head->next (把head变为当前head的下一个节点)
               NULL  temp->next = Phead (因为第一次循环Phead = NULL 所有temp的下一个节点为空)
	      [1->NULL]  temp(temp从1->2->3->4->5->6->7 变为 1->NULL 这里只是展示temp链表的变化)
		  [1->NULL]  Phead = temp
第二次循环
   2->3->4->5->6->7  temp = head
      3->4->5->6->7  head = head->next
  			1->NULL  temp->next = Phead
		 2->1->NULL  temp
		 2->1->NULL  Phead = temp
第三次循环
      3->4->5->6->7  temp = head
      	 4->5->6->7  head = head->next
         2->1->NULL  temp->next = head
      3->2->1->NULL  temp
      3->2->1->NULL  Phead = temp
依此类推
最终Phead 就会完成倒序 7->6->5->4->3->2->1 

递归法

LinkList reverse_3(LinkList head){
    if(head == NULL || head->next == NULL)
    {
        return head;
    }
    LinkList r_head = reverse_3(head->next);
    head->next->next = head;
    head->next = NULL;
    return r_head;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
三种不同的方法,挺不错的! #include<stdio.h> #include<stdlib.h> #include<string.h> #define N 100 typedef struct SList { char data[N]; //字符数组 struct SList *next; //定义链表头指针 }SList,*ListPointer; /*typedef struct List { SList *head; }List,* ListPointer; */ void initList(ListPointer &lp) { lp=(SList *)malloc(sizeof(SList));//初始化链表 lp->next=lp; //链表的头指针指向本身,实现链表循环 } void output(ListPointer lp) // 自定义输出函数 { SList *ep; ep=lp; while(ep->next!=lp) //判定条件 当指针重新指向头指针输出结束 { ep=ep->next; printf("%s ",ep->data); } } void revert(ListPointer lp) // 链表的逆置 { SList *p,*q; p=lp;q=NULL;lp=NULL; while(p) { q=p->next; p->next=lp; lp=p; p=q; } /*方法二 SList *p,*q,*end; p=lp->next; q=p->next; end=p; while(q!=lp) { lp->next=q; q=q->next; lp->next->next=p; p=lp->next; } end->next=lp; */ } void add_char(char *p,ListPointer lp) //将输入的字符传递给链表 { SList * ep; ep=lp; while(ep->next!=lp) //判定条件 当指针重新指向头指针输出结束 { ep=ep->next; } ep->next=(SList *)malloc(sizeof(SList)); //开辟空间存储 strcpy(ep->next->data,p); //字符的传递 ep->next->next=lp; } void main() { ListPointer L; char str[N]; initList(L); printf("输入#以结束\n");//确定输入终止条件 while(1) { scanf("%s",str); if(*str=='#') //判定条件 { break; } add_char(str,L); } printf("初始序列为:"); output(L); printf("\n"); revert(L); printf("逆置后为:"); output(L); printf("\n"); }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值