链表反转,合并和查倒数第几个的值。

本文详细介绍了链表的基本操作,包括元素反转、合并有序链表、查找倒数第k个节点等,并提供了对应的C语言代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

思路:
1.链表元素反转

  比如a->b->c->d 反转成 d->c->b->a

方法就是 a不动 把 b,c d,节点 依次反转如下:

a b c d


1. b a c d

2. c b a d

3 d c b a

2.  合并 (对两个有序链表的合并,合并后也为有序)

方法:比较两个节点,递归。


3. 查链表中倒数第几个节点。
 方法: 用两个指针 分别指向节点的头节点。

第一个指针先走k-1步。
然后第二个指针和第一个指针同时走 直到第一个指针为空,这是的第二个指针所指向的节点就为链表的倒数的第n个节点。


代码如下。

#include<stdlib.h>

typedef struct listNode {
    struct listNode  *next;
    int  data;
}listNode;

typedef struct list {
    struct listNode *head;
    unsigned long len;
}list;


listNode *MergeTwoList(listNode *head1,listNode *head2) {
   listNode *result =  NULL;
   if(head1==NULL) {
      return result;
   }
   if(head2==NULL) {
      return result;
   }
   if (head1->data<head2->data) {
       result = head1;
       result->next  = MergeTwoList(head1->next,head2);
   }
   else {
      result = head2;
      result->next = MergeTwoList(head1,head2->next);
  }
  return result;
}

listNode *FindKthToTail(list *plist,int k) {
   if(plist->len<k) {
      printf("k is bigger than list's length");
      return NULL;
   }
   listNode *pahead=plist->head;
   listNode *pbehind = plist->head;
   unsigned int i=1;
   for(;i<k;i++) {
     pahead = pahead->next;
   }
   while(pahead->next != NULL) {
      pahead=pahead->next;
      pbehind = pbehind->next;
   }
   return pbehind;
}

void ReverseList(list *plist) {    //反转
    listNode *pnode = plist->head;
    while(pnode->next!=NULL) {
        listNode *p2 = pnode->next;
        listNode *p3 = NULL;
        if(p2!=NULL) {
            p3 = p2->next;
        }
        p2->next = plist->head;
        plist->head = p2;
        pnode->next=p3;
    }
}

list *createlist(void) {
    list *plist = (list*)malloc(sizeof(list));
    if (plist == NULL) {
        printf("error in creating the list.\n");
        return NULL;
    }
    plist->head = NULL;
    plist->len=0;
    return plist;
}
void insertlistNode(list *plist,int data) {
    //create a new noce.
    listNode *pnode = (listNode *) malloc(sizeof(listNode));
    pnode->next=NULL;
    pnode->data = data;
    if(plist->len ==0) {
        plist->head = pnode;
        plist->len = 1;
    } else {
        pnode->next = plist->head;
        plist->head = pnode;
        plist->len++;
    }
}

void loop(list *plist) {
    listNode *pNode = plist->head;


    while(pNode!=NULL) {
        printf("%d\n",pNode->data);
        pNode=pNode->next;
    }
}

void main() {
 list *glist = createlist();
 int i=1;
 for(;i<10;i++) {
    insertlistNode(glist,i);
  }
  printf("print the input list\n");
  loop(glist);
  ReverseList(glist);
  loop(glist);

....

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值