单链表的就地逆置(头插法)

    xiaoxiao2022-07-05  155

    头插法(图示) 1.原链表 2.链表的初始化:定义两个指针p,q,p用来保存下一个需要逆置的节点,q指向目前要逆置的节点

    //准备工作 p=head->next; head->next=NULL; q=p;

    3.第一个节点的逆置

    //逆置 q->next=head->next; head->next=q; //第二个节点逆置的准备工作 q=p; p=p->next;

    3.第二个节点的逆置

    //逆置 q->next=head->next; head->next=q; //第三个节点的逆置准备工作 q=p; p=p->next;

    … … …直到p==NULL时跳出循环(逆置和准备工作部分操作统一,可放在循环中) 主要部分代码

    struct num*_oppose(struct num*head) { struct num*p, *q; p = head->next; head->next = NULL; while (p) { q = p; p = p->next; q->next = head->next; head->next = q; } return head; }

    以6个节点的链表为例,进行链表的逆置,完整代码如下:

    //节点的定义 struct num { int n;//数据部分 struct num*next;//指针部分 }; //单链表的建立 struct num*_creat() { int num[6] = { 1,2,3,4,5,6 }; int i; struct num*head, *end, *new; head = end = (struct num*)malloc(sizeof(struct num)); head->next = NULL; end = head; for (i = 0; i < 6; i++) { struct num*new; new = (struct num*)malloc(sizeof(struct num)); new->next = NULL; new->n = num[i]; end->next = new; end = new; } return head; } //单链表的遍历 struct num*_print(struct num*head) { struct num*p; p = head->next; while (p) { printf("=", p->n); p = p->next; } printf("\n"); } //逆置部分 struct num*_oppose(struct num*head) { struct num*p, *q; p = head->next; head->next = NULL;//初始化 while (p) { q = p; p = p->next; q->next = head->next; head->next = q; } return head; } int main(void) { struct num*head, *end; head = _creat(); _print(head); _oppose(head); _print(head); return 0; }

    运行结果

    最新回复(0)