链表翻转程序

今天看到面试题里面有个链表翻转程序,一时兴起写了一个,第一次竟没得到正确结果,调了半天才出来,稍有惭愧。

 

#include  < stdio.h >
#include 
< stdlib.h >


struct  Node {
    
int data;
    
struct Node* next;
}
;

void  orderinsert(Node *&  head, Node *&  n) {
    Node
* t=head;
    Node
* pre=NULL;
    
while (t && t->data<=n->data)
    
{
        pre
=t;
        t
=t->next;
    }

    
if(pre)
        pre
->next=n;
    
else
        head
=n;
    n
->next=t;
}

void  sort(Node *&  head) {
    Node
* t=head;
    Node
* h=NULL;
    Node
* x=NULL;
    
while (t)
    
{
        x
=t->next;
        orderinsert(h,t);
        t
=x;
    }

    head
=h;
}


void  reverse(Node *&  head) {
    Node
* pre=NULL;
    Node
* n=NULL;
    Node
* t=head;
    
while (t->next)
    
{
        n
=t->next;
        t
->next=pre;
        pre
=t;
        t
=n;
    }

    t
->next=pre;
    head
=t;
}


void  printlist(Node *  p) {
    printf(
"list is:  ");
    
while (p)
    
{
        printf(
"%d ",p->data);
        
if(p->next)
            p
=p->next;
        
else
            
break;
    }

    printf(
" ");
}

void  main() {

    
int linklen=0;
    Node
* head=NULL;
    Node
* tail=NULL;
    Node
* p=NULL;
    printf(
"input ink length: ");
    scanf(
"%d",&linklen);
    
if (linklen<=0)
    
{
        printf(
"error length.");
        
return;
    }

    
for(int i=0;i<linklen;i++)
    
{
        p
=(Node*)malloc(sizeof(Node));
        p
->next=NULL;
        printf(
"input num %d data ",i);
        scanf(
"%d",&(p->data));
        
//按顺序插入
        orderinsert(head,p);
    }

    printlist(head);
    
//翻转
    reverse(head);
    printlist(head);
    
//再次从小到大排序
    sort(head);
    printlist(head);

}
;
链表翻转是指将一个单向链表中的所有节点顺序翻转。以下是一个简单的C++程序实现链表翻转: ```c++ #include <iostream> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; ListNode* reverseList(ListNode* head) { ListNode* prev = NULL; ListNode* curr = head; while (curr != NULL) { ListNode* nextTemp = curr->next; curr->next = prev; prev = curr; curr = nextTemp; } return prev; } int main() { ListNode* head = new ListNode(1); head->next = new ListNode(2); head->next->next = new ListNode(3); head->next->next->next = new ListNode(4); cout << "Original list: "; ListNode* curr = head; while (curr != NULL) { cout << curr->val << " "; curr = curr->next; } cout << endl; head = reverseList(head); cout << "Reversed list: "; curr = head; while (curr != NULL) { cout << curr->val << " "; curr = curr->next; } cout << endl; return 0; } ``` 在上面的代码中,我们定义了一个ListNode结构体表示链表的节点,包含一个整数值和一个指向下一个节点的指针。reverseList()函数实现了链表翻转操作,它使用了三个指针prev、curr和nextTemp。prev指向上一个节点,curr指向当前节点,nextTemp指向下一个节点。在while循环中,我们不断将当前节点的指针指向上一个节点,然后更新三个指针的值以便继续循环。最后返回prev作为新链表的头节点。在main函数中,我们创建了一个包含四个节点的链表,并输出原始链表翻转后的链表
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值