反转链表

来源:互联网 发布:手机锁帧软件 编辑:程序博客网 时间:2024/06/06 04:50

输入一个链表,反转链表后,输出链表的所有元素。


C++:

/*struct ListNode {int val;struct ListNode *next;ListNode(int x) :val(x), next(NULL) {}};*/class Solution{public:ListNode* ReverseList(ListNode* phead){ListNode *h=NULL;for(ListNode *p=phead; p; ){ListNode *tmp=p->next;p->next=h;h=p;p=tmp;}return h;}};

Java:

/*public class ListNode {    int val;    ListNode next = null;    ListNode(int val) {        this.val = val;    }}*/public class Solution{    public ListNode ReverseList(ListNode head){if(head==null) return null;ListNode pre=null, next=null;while(head!=null){next=head.next;head.next=pre;pre=head;head=next;}return pre;}}